#include <unistd.h>
pid_t fork(void);
Returns: 0 in child, process ID of child in parent,?1 on error
#include "apue.h"
#include "myerr.h"
int globvar=6;/*external variable in initialized data */
char buf[] = "a write to stdout\n";
int
main(void)
{
int var; /* automatic variable on the stack */
pid_t pid;
var = 88;
if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
err_sys("write error");
printf("before fork\n"); /* we don’t flush stdout */
if ((pid = fork()) < 0) {
err_sys("fork error");
}else if (pid == 0) { /* child */
globvar++; /* modify variables */
var++;
}else {
sleep(2); /* parent */
}
printf("pid = %ld, glob = %d, var = %d\n", (long)getpid(), globvar, var);
exit(0);
}
windeal@ubuntu:~/Windeal/apue$ ./exe
a write to stdout
before fork
pid = 4523, glob = 7, var = 89
pid = 4522, glob = 6, var = 88
windeal@ubuntu:~/Windeal/apue$
#include "apue.h"
#include "myerr.h"
int globvar=6;/*external variable in initialized data */
int
main(void)
{
int var; /* automatic variable on the stack */
pid_t pid;
var = 88;
printf("before vfork\n"); /* we don’t flush stdio */
if ((pid = vfork()) < 0) {
err_sys("vfork error");
}else if (pid == 0) { /* child */
globvar++; /* modify parent’s variables */
var++;
_exit(0); /* child terminates */
}
/* parent continues here */
printf("pid = %ld, glob = %d, var = %d\n", (long)getpid(), globvar, var);
exit(0);
}
~
windeal@ubuntu:~/Windeal/apue$ ./exe
before vfork
pid = 6298, glob = 7, var = 89
windeal@ubuntu:~/Windeal/apue$
APUE学习笔记——8.3~8.4创建新进程fork()、vfork()
原文地址:http://blog.csdn.net/windeal3203/article/details/38924869