繁体   English   中英

如何在两个过程之间进行简单的同步

[英]how to make a simple synchronization between two processes

嗨,我有一个关于程序的作品,就像一个孩子应该将一个数字打印到文本文件中,而第二个孩子应该将这个数字同时打印到屏幕上。 但是我的代码可以正常工作,就像第一个孩子完成打印数字09 ,然后第二个孩子开始将它们读到屏幕上一样。 所以我想这是一个同步问题。 这是我的简单代码;

#include <stdio.h>     /* basic I/O routines.   */
#include <unistd.h>    /* define fork(), etc.   */
#include <sys/types.h> /* define pid_t, etc.    */
#include <sys/wait.h>  /* define wait(), etc.   */
#include <signal.h>    /* define signal(), etc. */
#include <pthread.h>

void write_num(void);
void print_screen(void);
//void catch_child(int);

int main(int argc, char* argv[]) {

        int i, result, pid;

        pid = fork(); /* creates a new process, you only want the parent to spawn children? */

        switch (pid) {

             case -1:
                /* fork error */
                printf("Error occured with fork()\n");
                exit(1);
             case 0:
                /* child process */
                write_num(); 
                exit(0);
             default:
                 /* parent process*/
                {
                //wait(&pid);
                pid = fork(); /* fork new children here */


                switch(pid) {

                    case -1:
                        printf("Error occured with fork()\n");
                        exit(1);

                    case 0: 

                        print_screen();
                        exit(0);

                    default:
                        break;

                         }
                }
     }
    wait(&pid);
    execl("/usr/bin/killall","killall","tail",(char *) 0);
    return 0;
}

void write_num(void){

 FILE* fptr;
 int i;

 fptr=fopen("textfile.txt","w");

    for(i=0; i<10; i++){

        fprintf(fptr,"%d\n",i);
        fflush(stdout);
        sleep(1);

        }
}

void print_screen(void){

        execl("/usr/bin/tail","tail","-f","./textfile.txt",(char *) 0);
        sleep(1);

}

/* first, here is the code for the signal handler
void catch_child(int sig_num)
{
     when we get here, we know there's a zombie child waiting
    int child_status;

    wait(&child_status);
    printf("child exited.\n");
}*/

顺便说一句,在Ubuntu中,我曾经使用gcc -o process process.c -lpthread进行编译。

如果您可以提供帮助,我们将不胜感激。

您需要更改为

flush(fptr);  

您可能要考虑让主进程创建两个子线程而不是进程。 子线程A可以写入文件,而子线程B将显示该数字。 当有新的数字可用时,主线程可以调度这两个子线程。

无需根据您的问题陈述进行任何同步,只需将数字同时输出到屏幕和文件即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM