寫出產生 child process 之程式

2009-03-27 11:40 pm
寫出產生 child process 之程式
需要用到 fork() 和 exec() ( execlp() )

程式輸出內容

parent process : I'm parent
child process : I'm child

另外 程式不能使用function call ex:printf()
只能使用System call ex:exec()
更新1:

請問version 2呢@@? 還有程式輸出內容要是 parent process : I'm parent child process : I'm child 謝謝!

回答 (2)

2009-03-28 11:44 am
✔ 最佳答案
Can I use system call write()?

2009-03-28 03:44:50 補充:
2 versions:
Version #1:

#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>

int main()
{
pid_t pid;
int return_v;

switch(pid=fork()) {
case -1:
perror("fork");
exit(1);

case 0:
execl("/bin/sh", "sh", "-c","echo \"I'm child\"", NULL);
exit(return_v);

default:
execl("/bin/sh", "sh", "-c","echo \"I'm parent\"", NULL);
exit(return_v);
wait(&return_v);
}
}

Version #2:

2009-03-31 22:30:11 補充:
Can you send me an e-mail? I have exceeded my 300 words limit.

2009-03-31 22:52:00 補充:
See if you can get this:
For the output, you can change the execl lines to:
execl("/bin/sh", "sh", "-c","echo \"child process: I'm child\"", NULL);
execl("/bin/sh", "sh", "-c","echo \"parent process:I'm parent\"", NULL);

2009-03-31 22:53:37 補充:
For V2:
Change the execl lines to:
write(0,"child process: I'm child\n",26);

2009-03-31 22:53:56 補充:
write(0,"parent process: I'm parent\n",28);
2009-03-28 6:03 am
你的要弄linux才能寫說~


收錄日期: 2021-04-30 13:08:59
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090327000016KK05024

檢視 Wayback Machine 備份