fork 等函数编写执行命令实验

【实验目的】
本实验将通过编写 fork 和 exec 等系统调用的程序,加深对系统进程及其控制的了解。
【实验原理】
fork 后调用 exec 族函数来调用系统命令或者程序来实现系统 shell 功能。
【实验内容】
10.1 execv 函数族的使用
注意:调用 execv 后,程序不再返回!在上述代码基础上,在子进程的退出代码前加入如下代码:

printf("global=%d test%d Child,my PID is %d\n",global,test,getpid());
if(execl("/bin/ps","ps","-au",NULL)<0)
perror("execl error!");
printf("this message will never be printed!\n");
exit(0);

编译运行后结果为:
[root@localhost root]# ./test

the test content!
fork test!
global=23 test=1 Child,my PID is 2909
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 2719 0.0 0.6 4360 1032 pts/1 S 23:14 0:00 /bin/bash
root 2908 0.0 0.1 1340 276 pts/1 R 23:38 0:00 ./test
root 2909 0.0 0.4 2684 736 pts/1 R 23:38 0:00 ps -au
global=25 test=3 Parent,my PID is 2908

10.2 Waitpid
waitpid 的作用是等待子进程退出并回收其资源,同时可以通过 WIFEXITED 等宏调用可以检测子
进程退出的状态。在第一个示例 fork 使用的代码基础上进行修改,添加检测进程退出状态的子函数,
参考代码如下:

void exit_check(int stat)
{
if (WIFEXITED(stat))
{ printf("exit normally!the return code is: %d \n",WEXITSTATUS(stat)); }
else if (WIFSIGNALED(stat))
{ printf("exit abnormally!the signal code is: %d \n",WTERMSIG(stat)); }
}

在父进程处理 global 和 test 变量前加入如下代码:

if (waitpid(pid,&stat,0) == pid)
{ exit_check(stat); } // the status of exit check

编译运行后结果为:

[root@localhost root]# ./test
the test content!
fork test!
global=23 test=1 Child,my PID is 2973
exit normally!the return code is: 0
global=24 test=2 Parent,my PID is 2972

可以看出父进程回收了退出的子进程的资源,检测到了它的退出状态。

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

STM32单片机定制

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值