源程序是這樣:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int ret = 0;
ret=system("ifconfig | grep eth7");
printf("ret=%d \n",ret);
if (0 == ret)
{
printf("error");
}
printf("exit!!");
}
函數執行結果發現:
eth7 Link encap:Ethernet HWaddr 00:0c:29:0e:30:e1
ret=0
后面的error和exit都打印不出來了。
求高人解答!
11 个解决方案
樓主,我剛試了下,運行正常
至於你機子出問題,也在情理之中。出問題原因就是 system()會調用fork()產生子進程,在創建了fork子進程執行ipconfig命令時,因為存在部分時間運算處理,導致了子進程跟父進程數據處理不同步.同時,ret實際得到直並非0,只不過前一次輸出強制轉換為0,在后面比較運算中,進程發生錯誤,直接exit退出
測試了下沒有問題啊。。試試出錯的情況。。比如eth10什么的
[root@localhost test]# ./a.out
eth0 Link encap:Ethernet HWaddr 08:........
ret = 0
error[root@localhost test]#
在每個最后不帶\n的printf后面加fflush(stdout);
在每個不想受接收緩沖區舊內容影響的scanf前面加rewind(stdin);
另外請檢查scanf的返回值。
usage: ifconfig -a [ -m ] [ -d ] [ -u ] [ af ]
ifconfig -l [ -d ] [ -u ]
ifconfig [ -m ] interface
[ af [ address [ dest_addr ] ] [ netmask mask ] [ broadcast addr ]
[ alias ] [ delete ] ]
[ up ] [ down ] [ detach ]
[ af first[alias] address [ ... ] ]
[ site6 site_number ]
[ metric n ]
[ mtu n ]
[ arp | -arp ]
[ link0 | -link0 ] [ link1 | -link1 ] [ link2 | -link2 ]
ret=256
exit!!
輸出這個東西 呵呵