C语言进程控制
1、编程写程序实现:一个进程产生子进程,
(1) 子进程每隔5秒打印出“Hello,I am child”,共打印十次,十次打印完毕后输出“child finished task”;
(2) 父进程每隔2秒钟打印“Hello,I am father”,共打印5次,5次打印完毕后输出“father finished task”;
(3) 当父进程判断子进程退出后输出“My son is gone ,so I ought to go away,too!”
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
pid_t result;
if((result=fork())==-1){
perror("run error!\r\n");
}else if(result==0){
// in child
int childCount=0;
while(1){
sleep(5);
printf("%d-Hello,I am child!\r\n",childCount+1);
childCount++;
if(childCount==10){
printf("child finished task!\r\n");
break;
}
}
}else if(result>0){
// in parent
int parentCount=0;
while(1){
sleep(2);
printf("%d-Hello,I am father!\r\n",parentCount+1);
parentCount++;
if(parentCount==5){
printf("father finished task!\r\n");
break;
}
}
pid_t childSatus=wait(NULL);
while(childSatus>0){
printf("My son is gone ,so I ought to go away,too!\r\n");
break;
}
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RVIrW6Fg-1615953459543)(C:%5CUsers%5Cxlu%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20210317115351134.png)]
- 编译为ARM板上的可执行文件
arm-linux-gnueabi-gcc -o 文件名 源文件.c