我正在尝试编写一个函数,它将按字符串中的程序名称来杀死实例
unsigned int kill_all_program_instances(const char * program_name){
int res;
char buf[1024];
string first;
string second;
int lSize, pid , pos;
string command="pidof ";
FILE *fd;
memset(buf,'\0',sizeof(buf));
fd=popen((command+program_name).c_str(),"r");
unsigned int mypid = getpid();
if(fd != NULL){
fseek (fd , 0 , SEEK_END);
lSize = ftell(fd);
rewind (fd);
if (lSize <= 0)
{
printf("lsize is %d\n",lSize);
pclose(fd);
return 0;
}
.....
}
Run Code Online (Sandbox Code Playgroud)
这只是函数的开头,但我总是为lSize得到-1.我跑了
pidof chromium-browse
Run Code Online (Sandbox Code Playgroud)
得到了
26487 19353 16993 11504 10960 10880 10868 10829 10825 10805 8607 8263 8154 8089 7764 3965 3950
Run Code Online (Sandbox Code Playgroud)
但是当我跑步的时候
kill_all_program_instances('chromium-browse')
Run Code Online (Sandbox Code Playgroud)
对于lSize,我仍然得到-1.
我的代码有什么问题吗?
谢谢
除了关于检测错误的评论/答案popen(这似乎不正确)之外,我确实认为实际的问题是你试图在管道上使用fseek/ftell,这不是一个有效的操作.管道不是传统意义上的"文件",它是一个数据流,其中每个数据项只能读取一次.
只需阅读使用fscanf()或类似的东西,直到它给你一个EOF.
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |