关于linux的一些编程 (1)分别写一个小程序使用fork()、vfork或clone()创建子进程。 (2)比较他们的运行

2025-04-04 22:27:39
推荐回答(1个)
回答1:

你说的问题我也不太懂,不过我这有些代码可以给你参考下:
建立一个新的进程forkdemo1.c:
/* forkdemo1.c
* shows how fork creates two processes, distinguishable
* by the different return values from fork()
*/

#include

main()
{
int ret_from_fork, mypid;

mypid = getpid(); /* who am i? */
printf("Before: my pid is %d\n", mypid); /* tell the world */

ret_from_fork = fork();

sleep(1);
printf("After: my pid is %d, fork() said %d\n",
getpid(), ret_from_fork);
}
子进程创建进程frokdemo2.c:
/* forkdemo2.c - shows how child processes pick up at the return
* from fork() and can execute any code they like,
* even fork(). Predict number of lines of output.
*/

main()
{
printf("my pid is %d\n", getpid() );
fork();
fork();
fork();
printf("After, my pid is %d\n", getpid() );
}
分辨父进程和子进程forkdemo3.c:
/* forkdemo3.c - shows how the return value from fork()
* allows a process to determine whether
* it is a child or process
*/

#include

main()
{
int fork_rv;

printf("Before: my pid is %d\n", getpid());

fork_rv = fork(); /* create new process */

if ( fork_rv == -1 ) /* check for error */
perror("fork");

else if ( fork_rv == 0 )
printf("I am the child. my pid=%d\n", getpid());
else
printf("I am the parent. my child is %d\n", fork_rv);
}
父进程等待子进程的退出waitdemo.c:
/* waitdemo.c - shows how parent pauses until child finishes
*/

#include

#define DELAY 2

main()
{
int newpid;
void child_code(), parent_code();

printf("before: mypid is %d\n", getpid());

if ( (newpid = fork()) == -1 )
perror("fork");
else if ( newpid == 0 )
child_code(DELAY);
else
parent_code(newpid);
}
/*
* new process takes a nap and then exits
*/
void child_code(int delay)
{
printf("child %d here. will sleep for %d seconds\n", getpid(), delay);
sleep(delay);
printf("child done. about to exit\n");
exit(17);
}
/*
* parent waits for child then prints a message
*/
void parent_code(int childpid)
{
int wait_rv; /* return value from wait() */
wait_rv = wait(NULL);
printf("done waiting for %d. Wait returned: %d\n", childpid, wait_rv);
}