首页 > 解决方案 > 如何运行在后台从标准输入读取字符串的 C++ 程序?

问题描述

我有一个 C++ 程序,它在循环中从标准输入读取字符串,当我运行它时,它工作得很好。现在我想在后台运行它。

首先我尝试nohup ./myprog &了,但是nohup.out程序的输出(“”)会很快增加invalid order

然后我试了一下nohup ./myprog </dev/null &,现象还是一样。

我想知道:

  1. 有什么技巧可以在 Linux 的后台运行我的程序吗?
  2. nohup见面的时候cin,发生了什么?为什么我的程序输出invalid order

我的 C++ 代码如下:

#include <iostream>
#include <string>
#include <thread>
using namespace std;

#include <stdlib.h>

void domybusiness()
{
    // do my business
}

int main()
{
    thread t(domybusiness);
    t.detach();

    string order;
    while (true)
    {
        cin >> order;
        if(order == "exit")
        {
            exit(0);
        }
        else if(order == "other cmd")
        {
            // other process
        }
        else
        {
            cout << "invalid order" << endl;
        }
    }

    return 0;
}

标签: c++linuxshell

解决方案


推荐阅读