您的位置:首页 > 运维架构 > Linux

Forking and executing process

2017-07-12 10:43 399 查看

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐