⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test1.c

📁 华清远见应用培训班例程源码
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>#include <string.h>#include <errno.h>int main(int argc, char **argv){  // pid_t fork(void);  pid_t pid;  int parent_int_data = 1000;  char *parent_string_data = "Just a test.\n";  int i;  for (i = 0; i < 3; i++)  {    fprintf(stdout, "[%d]DEBUG: call fork() %d\n", getpid(), i);    pid = fork();    // XXX: Otherwise,  -1  shall  be returned  to  the  parent  process,  no child process shall be created, and errno shall be set to indicate the error.    if (pid < 0)    {      // FIXME: deal with this error.      fprintf(stderr, "ERROR: call fork() failed: errno=%d, error message: %s\n", errno, strerror(errno));      switch (errno)      {	case EAGAIN:	  fprintf(stderr, "The error is EAGAIN.\n");	  break;	case ENOMEM:	  fprintf(stderr, "The error is ENOMEM.\n");	  break;	default:	  fprintf(stderr, "Other error.\n");	  break;      }      exit(1);    }    // XXX: Upon successful completion, fork() shall return 0 to the child process and  shall return  the process ID of the child process to the parent process. Both processes shall continue to execute from  the  fork()  function.      if (pid == 0)    {#ifdef _DEBUG_      fprintf(stdout, "[%d]DEBUG: I'm child process, my pid = %d\n", getpid(), getpid());      fprintf(stdout, "[%d]DEBUG: My parent pid = %d\n", getpid(), getppid());      fprintf(stdout, "[%d]DEBUG: current i = %d\n", getpid(), i);#endif      fprintf(stdout, "[%d]DEBUG: parent_int_data = %d\n", getpid(), parent_int_data);      fprintf(stdout, "[%d]DEBUG: parent_string_data = %s\n", getpid(), parent_string_data);      // XXX: Here call exit() to quit is very important.      //exit(0);      //sleep(5);    }    else if (pid > 0)    {#ifdef _DEBUG_      fprintf(stdout, "[%d]DEBUG: I'm parent process, my pid = %d, the new created child process pid = %d\n", getpid(), getpid(), pid);      fprintf(stdout, "[%d]DEBUG: My parent pid = %d\n", getpid(), getppid());      fprintf(stdout, "[%d]DEBUG: current i = %d\n", getpid(), i);#endif      fprintf(stdout, "[%d]DEBUG: parent_int_data = %d\n", getpid(), parent_int_data);      fprintf(stdout, "[%d]DEBUG: parent_string_data = %s\n", getpid(), parent_string_data);    }    // TODO: do something.  }  return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -