system() call behavior

2019-08-03 08:20发布

问题:

I am using system() call to start "tail -f".

One thing I saw was that, invocation of tail takes 2 processes (I can see in ps): 1) sh -c tail filename 2) tail filename

As man page says: system() executes a command specified in command by calling /bin/sh -c command. I guess, process 1) is inevitable, correct?

I was just wondering if I can reduce number of processes from 2 to 1.

Thanks in advance.

回答1:

system always does sh -c command. If you want only one process, do system("exec tail -f").



回答2:

It's better to use fork()/exec() to launch processes. system() invokes the shell, so you should take care with what you pass to it.

/* Untested code, but you get the idea */
switch ((pid = fork())) {
case -1:
    perror("fork");
    break;
case 0:
    execl("/usr/bin/tail", "tail", "-f", filename);
    perror("execl");
    exit(1);
default:
    wait(pid);
    ...
}