1.编写程序,在程序中创建一个子进程,使父子进程分别打印不同的内容
#include#include #include int main(){ pid_t pid; pid=fork(); if(pid<0) { printf("error"); } if(pid==0) { printf("child process pid=%d,ppid=%d",getpid(),getppid()); } if(pid>0) { printf("parent process pid=%d,ppid=%d",getpid(),getppid()); } }
2.编写程序,在程序中创建一个子进程,是子进程通过exec更改代码段,执行cat命令
【解析】代码里面的arg是cat执行的命令 比如cat main.c cat
#include#include #include int main() { pid_t pid; pid = fork(); if (pid == -1) { perror("fork error"); exit(1); } else if (pid > 0) { printf("parent process:pid=%dn", getpid()); } else if (pid == 0) { printf("child process:pid=%dn", getpid()); char *arg[] = {"main.c", NULL }; execvp("cat", arg); perror("error execn"); printf("child process:pid=%dn", getpid()); } return 0; }



