📄 test2.c
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <errno.h>#include <string.h>#include <time.h>#define HELLOWORLD "Hello world!\n"#define GOODMORNING "Good morning!"int main(int argc, char **argv){ pid_t pid; int x; char *p; x = 99; if ((p = malloc(1024)) == NULL) { fprintf(stderr, "ERROR: call malloc() to allocate memory failed; %s, errno = %d\n", strerror(errno), errno); exit(1); } memcpy(p, HELLOWORLD, strlen(HELLOWORLD)); if ((pid = vfork()) < 0) { // FIXME: handle this fork error exit(1); } fprintf(stdout, "[%d] From here, parent process and child process will execute following section both.\n", getpid()); //fprintf(stdout, "[%d] x = %d.\n", getpid(), x); fprintf(stdout, "[%d] [%d] p = %x.\n", getpid(), time(NULL), p); fprintf(stdout, "[%d] [%d] string: %s.\n", getpid(), time(NULL), p); if (pid > 0) { // XXX: Parent process // TODO: continue fprintf(stdout, "[%d] I'm parent process, the new created child process is %d.\n", getpid(), pid); //fprintf(stdout, "[%d] x = %d.\n", getpid(), x); fprintf(stdout, "[%d] [%d] p = %x.\n", getpid(), time(NULL), p); fprintf(stdout, "[%d] [%d] string: %s.\n", getpid(), time(NULL), p);#if 0 if (p) { free(p); p = NULL; }#endif memcpy(p, GOODMORNING, strlen(GOODMORNING)); fprintf(stdout, "[%d] [%d] p = %x.\n", getpid(), time(NULL), p); fprintf(stdout, "[%d] [%d] string: %s.\n", getpid(), time(NULL), p); } else // pid == 0 { // XXX: child process pid_t self_pid, parent_pid; self_pid = getpid(); parent_pid = getppid(); fprintf(stdout, "[%d] I'm child process, my process id is %d, my parent process id is %d.\n", getpid(), getpid(), getppid()); sleep(5); //fprintf(stdout, "[%d] x = %d.\n", getpid(), x); fprintf(stdout, "[%d] [%d] p = %x.\n", getpid(), time(NULL), p); fprintf(stdout, "[%d] [%d] string: %s.\n", getpid(), time(NULL), p);#if 0 if (p) { free(p); p = NULL; }#endif // child process should release all resources allocated by parent process, including opened files, pointers, etc. // call exec() to launch a new process //exec("ls"); // call exit() to exit exit(0); // on exiting, child process will send a SIG_CHILD signal to parent process. } return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -