获取进程信息fork示例

这篇博客展示了在suse Linux环境下,如何通过C++程序获取并打印父进程和子进程的基本信息。文章通过一个包含fork()调用的示例程序,演示了如何创建子进程,并在子进程中修改全局和局部变量。程序中使用了两个exit(0)来清晰展示父子进程的不同状态。讨论了不使用exit(0)可能产生的结果以及子进程无限打印数据信息可能导致的后台持续执行情况。

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

 

Platform: suse Linux

 

Goal: print the basic information for parent process and child process

 

Steps:

compile and execute it.

 

Characteristic:

Two additional exit(0) are added into this program

 

Result:

system status information:
current process information:
pid: 30269
parent pid: 29390
user id: 73561
valid user id: 73561
group id: 16342
valid group id: 16342
end


a write to stdout
before fork
child process information:
current process information:
pid: 30270
parent pid: 30269
user id: 73561
valid user id: 73561
group id: 16342
valid group id: 16342
end


before fork
parent process information:
current process information:
pid: 30269
parent pid: 29390
user id: 73561
valid user id: 73561
group id: 16342
valid group id: 16342
end


 

Source Code:

 

#include "apue.h"

int     glob = 6;        /* external variable in initialized data */
char    buf[] = "a write to stdout/n";

void getProcessInformation();

int
main(void)
{
    int        var;        /* automatic variable on the stack */
    pid_t    pid;

    var = 88;
   
    std::cout << "system status information:" << endl;
    getProcessInformation();
   
    if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
    {
        std::cout << "write error!" << endl;
    }
   
    printf("before fork/n");    /* we don't flush stdout */

    if ((pid = fork()) < 0)
    {
        std::cout << "fork error" << endl;
    }
    else if (pid == 0)
    {
        std::cout << "child process information:" << endl;
        getProcessInformation();
        glob++;                    /* modify variables */
        var++;
        exit(0);
    } else
    {
        sleep(2);                /* parent */
        std::cout << "parent process information:" << endl;
        getProcessInformation();
        exit(0);
    }

    std::cout << "end this application:" << endl;
    getProcessInformation();
    printf("pid = %d, glob = %d, var = %d/n", getpid(), glob, var);
   
    exit(0);
}


void getProcessInformation()
{
    std::cout << "current process information:" << endl;
    std::cout << "pid: " << getpid() << endl;
    std::cout << "parent pid: " << getppid() << endl;
    std::cout << "user id: " << getuid() << endl;
    std::cout << "valid user id: " << geteuid() << endl;
    std::cout << "group id: " << getgid() << endl;
    std::cout << "valid group id: " << getegid() << endl;
    std::cout << "end/n/n" << endl;
   
    return;
}

 

使用了两个exit,目的是为了看的更加清晰。如果不使用,会有什么结果呢?待分析中。

 

如果在子进程中使用一个for循环一直不断的打印数据信息,那么很有可能一直在后台执行中。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值