- 编写一个程序,使其产生一个子进程c,并使用exec函数簇中的任意版本,使得子进程执行系统命令ls -l查看某个文件的详细信息,
父进程判断子进程是否执行成功?
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
int main()
{
pid_t son=fork();
if(son>0)
{
int status;
wait(&status);
if(WIFEXITED(status))
{
printf("正常退出,返回值为:%d\n",WIFEXITED(status));
}
}
if(son == 0)
{
int ret=execl("/bin/ls","ls","-l","day1.c",NULL);
if(ret == -1)
{
perror("execl error\n");
}
exit(0);
}
return 0;
}
- 写一个程序,创建嵌套的三个子进程,获取不同的子进程的父进程pid
尝试退出函数和等待函数waitpid监听
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
int main()
{
pid_t son1,son2,son3;
int status1,status2,status3;
int ret1,ret2,ret3;
son1=fork();
if(son1 == 0)
{
printf("父进程的pid=%d\n",getppid());
exit(10);
}
else if(son1 > 0)
{
son2=fork();
if(son2 == 0)
{
printf("父进程的pid=%d\n",getppid());
exit(15);
}
else if(son2 > 0)
{
son2=fork();
if(son2 == 0)
{
printf("父进程的pid=%d\n",getppid());
exit(20);
}
else if(son2 > 0)
{
printf("我是父进程3\n");
ret3=waitpid(-1,&status3,0);
}
printf("我是父进程2\n");
ret2=waitpid(-1,&status2,0);
}
printf("我是父进程3\n");
ret1=waitpid(-1,&status1,0);
}
printf("等待状态值1%d 状态值2%d 状态值3%d\n",ret1,ret2,ret3);
printf("等待退出值1%d 退出值2%d 退出值3%d\n",
WEXITSTATUS(status1),WEXITSTATUS(status2),WEXITSTATUS(status3));
return 0;
}