進(jìn)程fork

進(jìn)程參數(shù)? ? ps -aux 查看進(jìn)程命令

pid 進(jìn)程標(biāo)識號 ? ??

ppid 父進(jìn)程的pid


getpid()

pid_t pid=getpid(); ?得到進(jìn)程自己的pid


getppid()

pid_t pid=getppid();? 得到父進(jìn)程的pid


fork()


返回值 ?pid_t pid?父進(jìn)程:>0 返回值為子進(jìn)程pid ?子進(jìn)程:=0? 出錯(cuò):=-1?

fork調(diào)用之后,內(nèi)存中會(huì)出現(xiàn)兩個(gè)一樣的進(jìn)程,只是pid不同

fork調(diào)用原則

一次fork調(diào)用,就會(huì)產(chǎn)生兩個(gè)一樣的進(jìn)程,這兩個(gè)進(jìn)程是父子關(guān)系

在父進(jìn)程當(dāng)中調(diào)用fork,返回子進(jìn)程的PID

在子進(jìn)程中調(diào)用fork,返回0

對于父進(jìn)程和子進(jìn)程,首地址不同,但每個(gè)變量的偏移地址相同,子父進(jìn)程打印出來的是偏移地址

cpu: ?地址總線 ?數(shù)據(jù)總線 ?控制總線 ?

cpu尋址是基本地址+偏移地址尋址,所以cpu內(nèi)部有個(gè)基地址寄存器


wait(&status)

退出碼 WEXITSTATUS(status)

父進(jìn)程調(diào)用wait阻塞,等待子進(jìn)程結(jié)束后才返回,wait函數(shù)的參數(shù)是子進(jìn)程的退出值

pid_t pid = fork();

if (pid > 0) {

int status = 0;

wait(&status);

printf("wait的退出碼 %d\n", WEXITSTATUS(status));

} else if (pid == 0) {

sleep(10);

printf("子進(jìn)程結(jié)束");

return 250;

}

return 0;


文件描述符

父進(jìn)程和子進(jìn)程共享打開的文件描述符,一定要在fork之前打開

int fd = open("a.txt",O_RDONLY);

pid_t pid = fork();

char buf[1024];

if (pid ==-1) {

printf("forkerr + %s\n", strerror(errno));

exit(0);

}

if (pid > 0) { //父進(jìn)程

read(fd,buf.sizeof(buf));

printf("%s\n",buf);

pause();

}

if (pid == 0) { //子進(jìn)程

printf("子進(jìn)程+%d", getpid());

exit(0);

}

close(fd);

return 0;


exec()

char *args[] = { "/bin/ls", "-l", NULL};

execve("/bin/ls",args,NULL);

execve()第一個(gè)參數(shù)是執(zhí)行程序名,第二個(gè)是傳遞給執(zhí)行程序的main函數(shù)的args參數(shù)

和system(a 123)區(qū)別 ?: system會(huì)創(chuàng)建一個(gè)進(jìn)程 execve的進(jìn)程空間就被指定的程序占據(jù)


execv讀取另一個(gè)的進(jìn)程的文件描述符

myexecv.c

int fd = open("a.txt", O_RDONLY);

if (fd == -1) {

printf("error %s\n", strerror(errno));

return -1;

}

char **ss;

ss[0] = "a";

char stmp[10];

memset(stmp,0,sizeof(stmp));

sprintf(stmp,"%d",fd);

ss[1] = stmp;

ss[2] = NULL;

execve("a", ss, NULL); //通過ss傳遞參數(shù)args

a.c

int fd=atoi(args[1]);

char buf[1024];

memset(buf,0,sizeof(buf));

read(fd,buf,sizeof(buf));

printf("%s\n",buf);

return 0;



execv加fork保留原有進(jìn)程

myexecv.c

pid_t pid;

pid = fork();

int fd = open("a.txt", O_RDONLY);

if (fd == -1) {

printf("error %s\n", strerror(errno));

return -1;

}

if (pid == -1) {

printf("fork err %s", strerror(errno));

}

if (pid > 0) { //父進(jìn)程

pause();

} else { //子進(jìn)程

char *ss[3];

ss[0] = "a";

char stmp[10];

memset(stmp, 0, sizeof(stmp));

sprintf(stmp, "%d", fd);

ss[1] = stmp;

ss[2] = NULL;

execve("a", ss, NULL);

}

return 0;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容