简体   繁体   English

C ++:fork / exec还是pthread?

[英]C++ : fork/exec or pthread?

I'm writing a program, and once a button is pushed, I have to execute a server process (that will stop only if I decide to kill him). 我正在编写一个程序,一旦按下按钮,我就必须执行一个服务器进程(只有在我决定杀死他时才会停止)。
To execute this process, I decided to use fork/execv mechanism : 为了执行这个过程,我决定使用fork / execv机制:

void Command::RunServer() {

    pid = fork();

    if (pid==0) {
        chdir("./bin");
        char str[10];
        sprintf(str,"%d",port);
        char *argv[] = {"./Server", str};
        execv("./Server",argv);
    }
    else {
        config->pid = pid;
        return;
    }
}

And in the method "button pushed", I do: 在方法“按下按钮”,我做:

command->RunServer();

It seemed to work nicely a few days ago... and now i get error : 它似乎在几天前工作得很好......现在我得到错误:

main: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed.

Should I try to switch to pthread? 我应该尝试切换到pthread吗? Did I do something bad? 我做了坏事吗?

Thanks, 谢谢,
eo EO

When you do fork() all file descriptors of your process are duplicated in the new one. 当你执行fork() ,进程的所有文件描述符都会在新的文件描述符中重复。 And when you do exec*() all file descriptors are also kept, unless they are marked with the flag FD_CLOEXEC . 当你执行exec*()所有文件描述符也会被保留,除非它们标有FD_CLOEXEC标志。

My guess is that some fd used by some library (Xlib, probably) is inherited by the new process, and that the duplication is causing chaos in your program. 我的猜测是某些库使用的某些fd(可能是Xlib)是由新进程继承的,并且复制会导致程序混乱。

In these cases is useful the BSD function closefrom() ( closefrom(3) ) if you want to keep the standard I/O opened. 在这些情况下,如果要保持标准I / O打开,则BSD函数closefrom()closefrom(3) )非常有用。 Unfortunately, in linux there is no such function, so you have to do a close-all loop or similar cruft: 不幸的是,在linux中没有这样的功能,所以你必须做一个close-all循环或类似的cruft:

int open_max = sysconf (_SC_OPEN_MAX);
for (int i = 3; i < open_max; i++)
    close(i);

You can read more about this problem here . 您可以在此处详细了解此问题。

In the call to execv , argv has to be terminated by a null pointer. 在对execvargv必须由空指针终止。 The preceding line should be: 上一行应该是:

char* argv[] = { "./Server", str, NULL };

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

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