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循环一直不断的打印数据信息,那么很有可能一直在后台执行中。