Forking and executing process

7 篇文章 0 订阅

Summary

This passage tells you how to fork a child process and execute another command in child process on Linux.

Though we are using C library on Linux to do such stuff, however I would like to use C++ to handle outputs.

Libraries

  • unistd.h
  • iostream (For C++)
  • stdio.h (For C)

Code

#include<iostream>
#include<unistd.h>

using std::cout;
using std::endl;

int main(int argc, char* argv[]){
    pid_t fpid, sp;

    int retValue;

    if((fpid = fork()) < 0){
        cout<<"Error"<<endl;
    }else if(fpid == 0){
        cout<<"Child process PID: "<<getpid()<<endl;
        if(argc > 1){
            execl(argv[1], NULL);
        }
    }else{
        cout<<"Main process:"<<endl;
    }

    cout<<"Before wait"<<endl;

    sp = wait(&retValue);

    cout<<WEXITSTATUS(retValue)<<endl;
    cout<<sp<<endl;

    cout<<"After wait"<<endl;

    return 0;
}

Let’s say we have a program that prints Test and return 7 at the end of execution (return 7; in main).

Explanations

  • if((fpid = fork()) < 0): fork() returns -1 when it cannot start a process.
  • else if(fpid == 0): fork() returns 0 when it’s in child process.
  • else{cout<<"Main process:"<<endl;}: fork() returns PID when it’s main process.
  • cout<<"Son process PID: "<<getpid()<<endl;: Prints child process PID.
  • sp = wait(&retValue);: wait returns waited PID while &retValue passed pointer to retValue to wait(), and wait() will put process ended information into refValue.
  • cout<<WEXITSTATUS(retValue)<<endl;: WEXITSTATUS(retValue) gets return value in main() of the process.

Results

Run the code with YOUR_PROGRAM_NAME ANOTHER_PROGRAM while YOUR_PROGRAM_NAME is the compilation of codes above and ANOTHER_PROGRAM is another program that you want to execute in our program.

This code will print

Main process: # cout<<"Main process:"<<endl;
Before wait # cout<<"Before wait"<<endl;
Son process PID: 16608 # cout<<"Son process PID: "<<getpid()<<endl;
Test # Output of another program
7 # Return value of another in main
16608 # Child process PID
After wait # cout<<"After wait"<<endl;

on Terminal.

FYI, Phases after # are comments.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值