【问题标题】:Child and parent processes communicating asynchronously linux子进程和父进程异步通信linux
【发布时间】:2013-05-30 13:20:48
【问题描述】:

如何创建一个分叉并继续而不等待另一个完成?我编写了一个示例程序来说明我的问题。

该程序有一个计数程序,它只是从零开始计数,并每秒连续打印下一个数字。这是程序的父端,客户端坐在那里不断地等待用户输入。当用户输入一个数字时,计数变成这个数字,因为变量是共享的。这是代码

#include <sys/time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>   // Declaration for exit()

using namespace std;

struct Timer {
    int GetTimeMilli()
    {
        gettimeofday( &end,NULL);
        return int( (end.tv_sec - start.tv_sec )*1000) +
                int( (end.tv_usec- 
        start.tv_usec)/1000);
    }

    Timer()
    {
        ResetTimer();
    }
    //reset timer so start time becomes current time
    void ResetTimer()
    {
        gettimeofday( &start,NULL);
    }   
private:
    struct timeval start, end;


};

int num = 0;

int main()
{
    char* name = new char[256];

   pid_t pID = vfork();

   if (pID == 0) // child
   {
      // Code only executed by child process

      printf( "child process: \n");
      while(1)
      {
        cin.getline( name,20 );
        num = atoi( name);
      }
    }
    else if (pID < 0)            // failed to fork
    {
        cerr << "Failed to fork" << endl;
        exit(1);
        // Throw exception
    }
    else // parent
    {
      // Code only executed by parent process
        printf( "parent process:\n");
        Timer a;
        while(1)
        {

            if( a.GetTimeMilli() > 1000.0f )
            {
                a.ResetTimer();
                printf("%d\n",num);
                num++;
            }
        }
    }

    // Code executed by both parent and child.





    delete[] name;
    return 0;
}

【问题讨论】:

  • 因为变量是共享的” - 你的问题就在那里。变量在fork() 之后共享。对于这个问题,你最好使用std::thread
  • 正是我想要的,谢谢。另一个问题,我希望用户能够在控制台中输入,而控制台输出不会在用户输入时打印出用户输入的内容。我该怎么办?
  • 您能退后一步,告诉我们您要完成的工作吗?忘记进程和线程以及异步输入,只需告诉我们您的程序做了什么。套用一句名言,“所以你遇到了一个问题,你决定用线程解决它。现在你有两个问题。”
  • 基本上我正在编写服务器代码,它将打印出服务器信息,例如没有主机、没有客户端请求等。我还想要一个命令提示符交互,您可以在其中提取数据和设置变量,而不会阻塞程序。但是,在重新考虑之后,老实说,我可能会对其进行编辑,使其不会自动打印任何内容,并且您必须键入命令才能提取信息。

标签: c++ linux asynchronous input fork


【解决方案1】:

如果你在父进程中不为子进程wait,子进程就会变成所谓的zombie process,并且只要父进程存在,就会一直在系统中逗留。

如果不想在父进程中阻塞,可以使用waitpidWNOHANG选项进行轮询。

【讨论】:

  • 只要父进程存在,它就只会是僵尸。之后僵尸孩子将被 init 收割。
  • 感谢您的回复。问题是,我希望子进程在父母生活的所有时间都在那里。基本上我要运行的实际程序是一个服务器,其中有一个应用程序连续运行,打印出数据。应用程序的子应用程序接受用户输入来设置和获取程序中的变量;我不知道如何进行非阻塞输入,所以想法是孩子与程序交互而不阻塞它等待输入。
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多