← 返回首页
Linux高级程序设计(四十)
发表时间:2021-11-23 21:11:17
pause/abort函数

pause函数会使进程就会进入无限的休眠(暂停),直到遇到信号。

1.pause 函数原型:

#include <unistd.h>
int pause(void);

pause函数等待信号的到来(此函数会阻塞)。将调用进程挂起直至捕捉到信号为止。

实例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>  

int main(int argc, char *argv[])
{
    pid_t pid;
    int i = 0;

    pid = fork(); // 创建进程
    if (pid < 0)
    { // 出错
        perror("error to create process:");
    }

    if (pid == 0)
    { // 子进程
       printf("I am son!\n");
       sleep(3);
       kill(getppid(),SIGINT);
    }
    else if (pid > 0)
    { // 父进程
      printf("I am father!\n");
      pause();  
    }
    return 0;
}

运行结果:

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
I am father!
I am son!

2.abort

函数原型:

#include <stdlib.h>
void abort(void);

abort函数向进程发送一个SIGABRT信号,默认情况下进程会退出。即使SIGABRT信号被加入阻塞集,一旦进程调用了abort函数,进程还是会被终止,且在终止前会刷新缓冲区,关闭文件描述符。

实例:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

int main(int argc, char *argv[])
{

    int num = 0;
    while (1)
    {
        printf("this is main()\n");
        sleep(1);
        num++;
        if(num==5){
            abort();
        }
    }
    return 0;
}

运行结果:

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
this is main()
this is main()
this is main()
this is main()
this is main()
Aborted