寫出產生 child process 之程式

寫出產生 child process 之程式

需要用到 fork() 和 exec() ( execlp() )

程式輸出內容

parent process : I'm parent

child process : I'm child

另外 程式不能使用function call ex:printf()

只能使用System call ex:exec()

Update:

請問version 2呢@@?

還有程式輸出內容要是

parent process : I'm parent

child process : I'm child

謝謝!

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    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);

  • 1 decade ago

    你的要弄linux才能寫說~

Still have questions? Get your answers by asking now.