如何在后台运行从标准输入读取字符串的 C++ 程序?

时间:2021-04-19 15:18:35

标签: c++ linux shell

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

首先我尝试了 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;
}

0 个答案:

没有答案
相关问题