ECF入门(上)

fork()指令

One call,Two return.返回值若为0,说明当前在子进程中;返回值大于0,说明在父进程中,返回值为其子进程的PID

getpid()

返回当前进程的ID

waitpid(pid_t pid,int *statusp,int options)

  • pid:

 pid>0时只等待进程ID为pid的子进程结束

 pid=-1时等待其所有的子进程中的任何一个(只要一个)结束

  • options:

 options=0(默认情况)时,挂起父进程,等待其子进程结束。返回子进程编号。

 options=WNOHANG时,父进程不挂起。如果一个子进程都没有结束的话,返回0;否则返回子进程编号。

  • 如果调用函数的进程没有子进程,waitpid返回-1,errno设为ECHILD

wait(&status)

等价于waitpid(-1,&status,0)

WIFEXITED(status):

如果子进程是以exit或者return正常退出的,函数返回值就为true

WEXITSTATUS(status)

前提是WIFEXITED一定为true,此函数返回正常终止的子进程的退出状态,即exit的值

atexit()

在进程结束调用exit时,调用atexit()括号中的注册函数,注册几次就调用几次。并且它的调用顺序和登记顺序是相反的。与压栈顺序有关。

相关习题

  • CSAPP书上部分

preparation:

1.http://csapp.cs.cmu.edu/public/code.html 下载.tar文件解压,包含了CSAPP书上的所有代码

2.运行sudo mv csapp.h /usr/include和sudo mv csapp.c /usr/include ,然后再usr/include中修改csapp.h在#endif 之前添加 #include"csapp.c"(我用的vi)

3.在gcc的时候最后加上-lpthread就可以

关于下列代码中用到的Fork和Wait在csapp.c中的定义:

/* $begin forkwrapper */
pid_t Fork(void)
{
   
    pid_t pid;

    if ((pid = fork()) < 0)
        unix_error("Fork error");
    return pid;
}
/* $end forkwrapper */

/* $begin wait */
pid_t Wait(int *status)
{
   
    pid_t pid;

    if ((pid  = wait(status)) < 0)
        unix_error("Wait error");
    return pid;
}
/* $end wait */

*8.11这个程序会输出多少个"hello"输出行?

#include "csapp.h"
int main()
{
   
	int i;
	
	for(i=0;i<2;++i)
		Fork();
	printf("hello\n");
	exit(0);
}

运行结果:
在这里插入图片描述
一共四行
进程图:在这里插入图片描述
*8.12这个程序会输出多少个hello输出行?

#include "csapp.h"
void doit()
{
   
    Fork();
    Fork();
    printf("hello\n");
    return;
}

int main()
{
   
    doit();
    printf("hello\n");
    exit(0);
}

在这里插入图片描述总共8行hello
进程图:
在这里插入图片描述
*8.13下面程序的一种可能的输出是什么?

#include "csapp.h"

int main()
{
   
    int x = 3;

    if (Fork() != 0)
	printf("x=%d\n", ++x);

    printf("x=%d\n", --x);
    exit(0);
}

运行结果:
在这里插入图片描述
在这里插入图片描述
可能的结果应该还有
在这里插入图片描述
在这里插入图片描述
*8.14下面这个程序会输出多少个"hello"输出行?

/* $begin forkprob5 */
#include "csapp.h"

void doit() 
{
   
    if (Fork() == 0) {
   
	Fork();
	printf("hello\n");
	exit(0);
    }
    return;
}

int main() 
{
   
    doit();
    printf("hello\n");
    exit(0);
}
/* $end forkprob5 */

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值