fork,waitpid实现守护进程

本文通过一个C++示例程序,展示了如何利用fork()创建子进程,并使用execvp()执行另一个程序,同时通过waitpid()等待子进程结束。此外,还介绍了如何通过信号值134判断子进程中assert断言失败的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

//g++ main.cpp -o main
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <assert.h>
using namespace std;
int main () {
    pid_t pid,wait_pid;
    int status;
    do {
        if ((pid = fork()) < 0) {
            cout << "error" << endl;
        } else if (pid == 0) {
            cout << "child_pid:" << getpid() << endl;
            sleep(2);
            execvp("./sub",0);
        } else {
            cout << "parent_pid:" << getpid() << endl;
            w = waitpid(pid,&status,0);
            cout << "w:" << w << " status:" << status << endl;
        }
    } while (134 == status);
    cout << "the end" << endl;
    return 0;
}
//g++ sub.cpp -o sub
#include <unistd.h>
#include <iostream>
#include <assert.h>
using namespace std;
int main () {
    cout << "sub child_pid:" << getpid() << endl;
    assert(1 < 0);
    return 0;
}

执行及结果:

#./main
parent_pid:29905
child_pid:29906
sub pid:29906
sub.cpp:7:int main():Assertion '1<0' failed.
w:29906 status:134
parent_pid:29905
child_pid:29908
sub pid:29908
sub.cpp:7:int main():Assertion '1<0' failed.
w:29908 status:134
parent_pid:29905
child_pid:29913
sub pid:29913
sub.cpp:7:int main():Assertion '1<0' failed.
w:29913 status:134

... ...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值