底辺SEの備忘録

スキル無しの底辺です。参考になりません。

Linuxのプロセス生成forkとexeclの違い

fork関数は呼び出したプロセスのコピープロセスを作成する

確認したプログラム

#include <stdio.h>
#include <unistd.h>

int main(void){
 pid_t pid;
 int i;
 printf("start\n");
 fork();
 pid=getpid();
 for(i=0;i<5;i++){
  printf("pid=%d i=%d\n",pid,i);
 }
}

実行結果

start
pid=6438 i=0
pid=6438 i=1
pid=6438 i=2
pid=6438 i=3
pid=6438 i=4
pid=6439 i=0
pid=6439 i=1
pid=6439 i=2
pid=6439 i=3
pid=6439 i=4

execl関数は別のプログラムを実行する

確認したプログラム

#include <stdio.h>
#include <unistd.h>

int main(void){
 printf("start\n");
 execl("/bin/ls","/bin/ls","-l",NULL);
 printf("finish\n");
 return 0;
}

実行結果
lsコマンドが実行される。別のプロセスに置換されるため「printf("finish\n");」は実行されない

start
合計 480
-rw-------. 1 root root   1795  4月 21 22:59 anaconda-ks.cfg
-rwxr-xr-x  1 root root   8456  5月  3 15:42 exe
-rw-r--r--  1 root root    149  5月  3 15:42 exe.c
-rw-r--r--  1 root root   7039  5月  3 15:45 exec.log.2943
-rw-r--r--  1 root root  28569  5月  3 15:44 exec.log.5652
-rwxr-xr-x  1 root root   8560  5月  1 21:44 flk
-rw-r--r--  1 root root    177  5月  1 21:44 flk.c
-rw-r--r--. 1 root root   1843  4月 21 23:00 initial-setup-ks.cfg
-rw-r--r--  1 root root 391626  4月 30 20:51 listener.log
-rw-r--r--  1 root root   7041  5月  3 15:23 test.log.2943
-rw-r--r--  1 root root   4542  5月  3 15:23 test.log.4314
-rw-r--r--  1 root root    292  5月  3 15:23 test.log.4315