Ccmmutty logo
Commutty IT
3 min read

pythonノートブックでC言語を実行

https://cdn.magicode.io/media/notebox/blob_mJejZpN
pythonのsubprocessを使って、c言語をコンパイル&実行できます。
python
#c言語のスクリプトを文字列に格納してファイルに書き込む。
code = """
#include <stdio.h>
int main(){
  puts("Hello, world!");
  return 0;
}
"""
with open("hello.c","w") as f:
  	f.write(code)
python
#ファイル確認
import os
print(os.listdir())

['.profile', '.bash_logout', '.bashrc', 'hello.c', '.ipython', '.jupyter-server-log.txt', '.cache', '.local', '.git', 'test.ipynb', 'requirements.txt']
python
#コンパイル
import subprocess
subprocess.run(["gcc","-o","hello","./hello.c"])
#helloがある
print(os.listdir())

['.profile', '.bash_logout', '.bashrc', 'hello.c', '.ipython', '.jupyter-server-log.txt', '.cache', 'hello', '.local', '.git', 'test.ipynb', 'requirements.txt']
python
#実行できる
print(subprocess.check_output(["./hello"]).decode())

Hello, world!
ノートブックセッションのメモリを試すこともできる。 関数wormは 自分のプロセスを再帰的に5個フォークすると同時に、double(8byte)*10000 = 80kbのメモリを予約。 ますますメモリ消費する様が見える。そして、フリーズする。
python
code = """
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>	
#include <sys/wait.h>	

#define NUM_WORKER 5

void worm(int egg){
  double* buf;
  pid_t  pid[NUM_WORKER];
  for(int i=0;i<NUM_WORKER;i++){
    pid[i] = fork();
    if(pid[i]==0){
      worm(1);
    }
  }
  if(egg){
    while(1){
      buf = (double*)malloc(sizeof(double)*10000);
      if(buf==NULL){
        puts("malloc fail");
      }
      buf = 0;
    }
  }
}


int main(){
  pid_t  pid[NUM_WORKER];
  for(int i=0;i<NUM_WORKER;i++){
    pid[i] = fork();
    if(pid[i]==0){
      worm(0);
    }
  }
  return 0;
}
"""
with open("worm.c","w") as f:
  	f.write(code)
print(os.listdir())

['.profile', '.bash_logout', '.bashrc', 'hello.c', '.ipython', '.jupyter-server-log.txt', 'worm.c', '.cache', 'hello', '.local', '.git', 'test.ipynb', 'requirements.txt']
python
#コンパイル
import subprocess
subprocess.run(["gcc","-o","worm","./worm.c"])
#wormがある
print(os.listdir())

['.profile', '.bash_logout', '.bashrc', 'hello.c', '.ipython', 'worm', '.jupyter-server-log.txt', 'worm.c', '.cache', 'hello', '.local', '.git', 'test.ipynb', 'requirements.txt']
メモリ監視用のライブラリpsutilを確認
python
#メモリの様子を見たいため、スレッドで実行
import threading
import time
import psutil


def bug():
  subprocess.run(["./worm"])
thread1 = threading.Thread(target=bug)
thread1.start()
thread1.join()


print(" used memory ")
while(True):
  print(psutil.virtual_memory())
  time.sleep(2)
動かなくなる

Discussion

コメントにはログインが必要です。