linux下fork指令

linux下运行以下代码

  1. 无选项编译链接
    用法:#gcc test.c
    作用:将test.c预处理、汇编、编译并链接形成可执行文件。这里未指定输出文件,默认输出为a.out。

  2. 选项 -o
    用法:#gcc test.c -o test
    作用:将test.c预处理、汇编、编译并链接形成可执行文件test。-o选项用来指定输出文件的文件名。

     #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后的。

#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); //更换代码段
    	}
    }

在这里插入图片描述
待子进程运行完后父进程再运行。

猜你喜欢

转载自blog.csdn.net/qq_36616602/article/details/83151355