2012年12月7日 星期五

父進程和子進程(fork , exec) , father process , child process



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

int main(void){
pid_t pid;
int number=0;

pid=fork();

if(0 == pid){ //child
printf("@@@ child number 1=%d\n",number);
number = 5;
printf("@@@ child number 2=%d\n",number);
execlp("/bin/ps","ps","-aux",NULL);  //your program
printf("@@@ child complete=%d\n",number); //if your program fail...
}else{ //father
printf("@@@ father number 1=%d\n",number);
number = 10;
printf("@@@ father number 1=%d\n",number);
wait(NULL);
printf("@@@ father complete=%d\n",number);
}

return 0;
}

gcc pthread.c -o test
./test

(1)由執行結果可以看出,子進程複製了父行程的變數,但已經在不同的記憶體中.
(2)由ps -aux 也可以看出的確有2個process出現.



沒有留言:

張貼留言