linux下fork指令

linux下運行以下代碼

  • 無選項編譯鏈接
    用法:#gcc test.c
    作用:將test.c預處理、彙編、編譯並鏈接形成可執行文件。這裏未指定輸出文件,默認輸出爲a.out。

  • 選項 -o
    用法:#gcc test.c -o test
    作用:將test.c預處理、彙編、編譯並鏈接形成可執行文件test。-o選項用來指定輸出文件的文件名。

1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{          
	pid_t val;
	printf("PID before fork(): %d \n",(int)getpid());
	val=fork();
	if ( val > 0) {
		printf("Parent PID: %d\n",(int)getpid());
	}else if (val == 0) {
		printf("Child PID: %d\n",(int)getpid());
	}else {
		printf(“Fork failed!);
		exit(1);
	}
}

在這裏插入圖片描述
當val等於0時,爲子進程,
當val等於1時,爲父進程。
子進程和父進程都運行,父進程運行val>0後的,子進程運行val==0後的。
2:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
       int main()
       {
        pid_t val; 
        int exit_code = 0;
        val=fork();
        	if (val > 0) {
        		int stat_val;
        		pid_t child_pid;
        		child_pid = waitpid(val,&stat_val,0);
        		printf("Child has finished: PID = %d\n", child_pid);
        		if(WIFEXITED(stat_val))
        			printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
        		else
        			printf("Child terminated abnormally\n");
        		exit(exit_code);
        	} else if (val == 0) {
        		execlp("ls","ls","-l",NULL); //更換代碼段
        	}
        }

在這裏插入圖片描述
待子進程運行完後父進程再運行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章