简体   繁体   中英

How to invoke an executable in the path /usr/bin using a C++ program?

I have an GUI based executable in the path /usr/bin in the linux machine This executable takes three arguments - two integer values and one char

Can you let me know how to invoke and run this executable from a user space C++ program

Not leaving this unanswered for no reason

pid_t runprocess(int arg1, int arg2, char arg3)
{
    static const char program[] = "/usr/bin/...";
    char arg1c[12];
    char arg2c[12];
    char arg3c[2];
    sprintf(arg1c, "%d", arg1);
    sprintf(arg2c, "%d", arg2);
    arg3c[0] = arg3;
    arg3c[1] = 0;
    pid_t pid = vfork();
    if (pid == 0) {
        signal(SIGHUP, SIG_IGN); /* since it's a GUI program, detach from console HUP */
        close(0); /* and detach from stdin */
        if (open("/dev/null", O_RDWR)) _exit(137); /* assertion failure */
        execl(program, program, arg1c, arg2c, arg3c, NULL);
        _exit(errno);
    }
    return pid;
}

Build arguments as strings, fork and exec it. Trivial really. Don't forget to wait() .

Since the child process is a GUI process, we detach HUP from the terminal we may or may not be running on and replace stdin with /dev/null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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