对system()的调用不会在C中给出预期的输出

时间:2015-08-17 10:07:09

标签: c bash grep

我编写此代码以检查名称为Field 1 = Country Field 2 = State (Based on what the user selected as as Country in Field 1) Field 3 = City (Based on what the user selected as State in Field 2) 的进程是否正在运行:

Rahul

此代码打印 int ret = -1; char cmd[40]="pgrep -f Rahul > /dev/null"; ret = WEXITSTATUS(system(cmd)); printf("%d\n", ret); ,表示存在名称包含0的进程,但我已验证此进程尚未运行。

我修改了代码并删除了输出重定向部分,因此修改后的代码为:

Rahul

此处输出为 int ret = -1; char cmd[40]="pgrep -f Rahul"; ret = WEXITSTATUS(system(cmd)); printf("%d\n", ret); ,即代码正常。

有人可以建议为什么会这样做吗?

1 个答案:

答案 0 :(得分:3)

你正面临着" bash"的特殊行为。结合" pgrep"。

首先,我们可以使用简单的命令简化问题:

$ strace -tt -F bash -c "pgrep -l -f Rahul" 2>&1 | egrep "exec|clone|dup|write"
19:47:50.336043 execve("/bin/bash", ["bash", "-c", "pgrep -l -f Rahul"], [/* 55 vars */]) = 0
19:47:50.343015 execve("/usr/bin/pgrep", ["pgrep", "-l", "-f", "Rahul"], [/* 54 vars */]) = 0
19:47:50.353342 read(4, "Name:\twriteback\nState:\tS (sleepi"..., 1024) = 538
19:47:50.387157 read(4, "egrep\0exec|clone|dup|write\0", 2047) = 27
19:47:50.387668 write(1, "3031 strace\n", 123031 strace

现在,我们可以看到每个人的内部结构:

$ strace -tt -F bash -c "pgrep -l -f Rahul > /dev/null" 2>&1 | egrep "exec|clone|dup|write"
19:48:44.669747 execve("/bin/bash", ["bash", "-c", "pgrep -l -f Rahul > /dev/null"], [/* 55 vars */]) = 0
19:48:44.676633 clone(Process 3046 attached
[pid  3046] 19:48:44.677336 dup2(3, 1)  = 1
[pid  3046] 19:48:44.677435 execve("/usr/bin/pgrep", ["pgrep", "-l", "-f", "Rahul"], [/* 54 vars */]) = 0
[pid  3046] 19:48:44.687636 read(4, "Name:\twriteback\nState:\tS (sleepi"..., 1024) = 538
[pid  3046] 19:48:44.727507 read(4, "egrep\0exec|clone|dup|write\0", 2047) = 27
[pid  3046] 19:48:44.728375 write(1, "3039 strace\n3045 bash\n", 22) = 22

与之相比:

SELECT js
FROM TableObject js
WHERE js
IN (
    SELECT jsa 
    FROM TableObject jsa 
    JOIN TableObject jsb 
    ON (
        jsa.job = jsb.job 
        AND jsa.key='power'
        AND jsa.value=:keyValue1 
        AND jsb.key = 'defense'
        AND jsb.settingValue=:keyValue2)) 
        AND js.job IN (
            SELECT j from OtherTableObject j where j.type = :type
        ) ORDER BY js.createDate DESC

只在第二个中看到一个"克隆"已经完成了。 " p纤ep"然后找到shell作为匹配过程。