unix/linux进程详解——代码

王朝学院·作者佚名  2016-08-27  
宽屏版  字体: |||超大  

#include <iostream>

#include <vector>

#include <cstdint>

#include <cstring>

#include <error.h>

#include <unistd.h>

using namespace std;

int main()

{

//system("ps aux &");//run on background

char *const ps_argv[]={"ps", "ax", 0};

//eg env

char *const ps_envp[]={"PATH=/bin:/usr/bin","TERM=console",0};

//possible exec

//execl("/bin/ps","ps","ax",0);//assume ps in the bin

//execlp("ps","ps","ax",0);//assume /bin is in the PATH

execle("/bin/ps","ps","ax",0,ps_envp);//pass own env

//execv("/bin/ps",ps_argv);

// execvp("ps",ps_argv);

// execve("/bin/ps",ps_argv,ps_envp);

// execlp("ps","ps","ax",0);

pid_t new_pid;

new_pid = fork();

new_pid = getpid();

cout << new_pid << endl;

switch (new_pid) {

case -1:

break;

case 0:

break;

default:

break;

}

cout << "errx" << endl;

return 0;

}

#include <iostream>

#include <vector>

#include <cstdint>

#include <cstring>

#include <error.h>

#include <unistd.h>

#include <sys/types.h>

using namespace std;

int main()

{

pid_t pid;

string message;

int n;

pid = fork();

//pid = getpid();

//cout << pid << endl;

switch (pid) {

case -1:

perror("fork failed");

exit(1);

case 0:

message = "this is the child";

n=5;

break;

default:

message = "this is the parent";

n=3;

break;

}

for(; n > 0;n--)

{

cout<<message<<endl;

sleep(1);

}

//cout << "errx" << endl;

return 0;

}

this is the parent

this is the child

this is the parent

this is the child

this is the parent

this is the child

$ this is the child

this is the child

#include <iostream>

#include <vector>

#include <cstdint>

#include <cstring>

#include <error.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/wait.h>

using namespace std;

int main()

{

pid_t pid;

string message;

int n;

int exit_code;

pid = fork();

//pid = getpid();

//cout << pid << endl;

switch (pid) {

case -1:

perror("fork failed");

exit(1);

case 0:

message = "this is the child";

n=5;

exit_code = 37;//casual set

break;

default:

message = "this is the parent";

exit_code = 0;

n=3;

break;

}

for(; n > 0;n--)

{

cout << message << ",which pid:" << getpid() << endl;

sleep(1);

}

if(pid != 0)

{

int stat_val;

pid_t child_pid;

child_pid = wait(&stat_val);

PRintf("child has finished: PID = %d\n",child_pid);

if(WIFEXITED(stat_val))

printf("child exited with code %d\n",WEXITSTATUS(stat_val));

else {

printf("child terminated abnormally\n");

}

}

//cout << "errx" << endl;

exit(exit_code);

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有