c - 同步父子进程

标签 c unix synchronization systems-programming

我想同步父进程和子进程以交替将 1 到 10 打印到文件中。并输出哪个进程打印了数字。以下代码交替打印,但数字相同。请帮帮我!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#define MSGSIZE 16
int parent= 1;
int n=-1;
main ()
{
  int i;
  char *msg = "How are you?";
  char inbuff[MSGSIZE];
  int p=0;
  FILE *fp1,*fp2;
  pid_t ret;

  ret = fork ();
  if (ret > 0)
    {
      i = 0;
      while (i < 10)
    {

      n++;
     // sprintf(msg, "%d", n);
     // fp=fopen("abc.txt","a");
     // write (p[1], itoa(n,msg,MSGSIZE), MSGSIZE);
     // sleep (2);
    // fclose(fp);
      //read (p[0], inbuff, MSGSIZE);

    fp1=fopen("abc.txt","r");
    fscanf(fp1,"%d",&n);
    fclose(fp1);
    fp1=fopen("abc.txt","w");
     fprintf(fp1,"%d",n); 
    printf("Parent: %d\n", n);
      i++;
    fclose(fp1);
    sleep(2);

    }
    exit(1);
    }
  else
    {
      i = 0;
      while (i < 10)
    {

      n++;
      //sleep (1);
     // read (p[0], inbuff, MSGSIZE);

     fp2=fopen("abc.txt","r");
     fscanf(fp2,"%d",&n);
     fclose(fp2);
     fp2=fopen("abc.txt","w");

     fprintf(fp2,"%d",n);        
      printf("Child: %d\n", n);
           i++;

     sleep(2);

    }
    }
  exit (0);
}

最佳答案

这是因为进程不共享内存,所以基本上每个进程的 n 都是不同的。为此,您需要使用进程间通信,Linux 提供了几种方法来实现此目的:

http://tldp.org/LDP/lpg/node7.html

一般来说,您只需要找到一种方法在父进程和子进程之间共享n的值即可。

注意:对于用户线程,不会出现此问题,因为同一进程上的用户线程共享内存。您只需要同步对其的访问即可。另外,请务必小心,因为根据您对进程使用的方法,您可能还需要同步访问。

关于c - 同步父子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10595012/

相关文章:

c - 如何在结构初始化中使用#define

c - UNIX 套接字权限 (Linux)

regex - 每行计数模式出现

c - sem_getvalue()引起的段错误

azure - AAD 应用程序注册中已存在属性标识符 Uris 具有相同值的另一个对象

c - 主线程调用pthread_exit后,它变成了僵尸。出了什么问题吗?

c - C三个堆栈并尝试所有选项

c++ - 在 CUDA 上乘以两个 float 变量

c++ - 从 c/c++ 代码更改 Linux 用户运行时

mysql - mysql中同步存储过程执行