linux下运行以下代码
-
无选项编译链接
用法:#gcc test.c
作用:将test.c预处理、汇编、编译并链接形成可执行文件。这里未指定输出文件,默认输出为a.out。 -
选项 -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); //更换代码段
}
}
待子进程运行完后父进程再运行。