system() call behavior

这一生的挚爱 提交于 2020-01-05 08:01:28

问题


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);
    ...
}


来源:https://stackoverflow.com/questions/6540023/system-call-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!