我有一个用 C 语言编写的程序,它用管道启动 mplayer,然后我通过该管道控制 mplayer。似乎有时当我通过管道发送命令时它会崩溃。以下是我的代码的相关部分以及我为调试它所做的工作。
原代码:
FILE *mplayer_pipe;
char temp[256];
bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
/* watch some values to see what to do next */
/* if I see a value that means I should stop mplayer I do this */
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
pclose(mplayer_pipe);
我遇到了一个问题,如果 mplayer 完成了,那么管道的另一端什么都没有,我仍然在停止我的程序崩溃。为了解决这个问题,我将其更改为以下内容:
FILE *mplayer_pipe;
char temp[256];
bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
/* watch some values to see what to do next */
/* if I see a value that means I should stop mplayer I do this */
FILE *mplayer_status;
int mplayer_pid = 0;
char status_read_char[256];
bzero(status_read_char,256);
mplayer_status = popen("pidof -s mplayer", "r");
fgets(status_read_char, 6, mplayer_status);
pclose(status_read_char);
mplayer_pid = atoi(status_read_char);
if(mplayer_pid > 0) {
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
pclose(mplayer_pipe);
}
else {
pclose(mplayer_pipe);
}
这个修复对我很有用,它不会崩溃。
然后我让其他人使用该程序,我开始每隔一段时间就会崩溃。由于我无法让我的程序自己崩溃,我将其更改为以下内容以查看程序崩溃的位置。
FILE *mplayer_pipe;
char temp[256];
bzero(temp,256);
sprintf(temp,"mplayer -quiet -slave video.mkv > mplayer.log");
mplayer_pipe = popen((char*)temp, "w");
printf("command: mplayer -quiet -slave video.mkv > mplayer.log");
/* watch some values to see what to do next */
/* if I see a value that means I should stop mplayer I do this */
FILE *mplayer_status;
int mplayer_pid = 0;
char status_read_char[256];
bzero(status_read_char,256);
mplayer_status = popen("pidof -s mplayer", "r");
fgets(status_read_char, 6, mplayer_status);
pclose(status_read_char);
mplayer_pid = atoi(status_read_char);
printf("mplayer_status: command: pidof -s mplayer. Got %s, value %d.",status_read_char,mplayer_pid);
if(mplayer_pid > 0) {
fputs("stop\n",mplayer_pipe);
fflush(mplayer_pipe);
printf("command: stop.");
pclose(mplayer_pipe);
}
else {
pclose(mplayer_pipe);
}
在我的程序下一次崩溃之前我得到的最后一件事是:
mplayer_status: command: pidof -s mplayer. Got 27323, value 27323.
对我来说,这表明它在将 stop 命令传递给 mplayer 时崩溃了。
有谁知道这里出了什么问题?以及如何防止它崩溃的任何想法?