我必须在linux上用C语言编写程序,可以使用mknod()函数控制mplayer。
当我用这个命令运行mplayer时
mplayer -input file=/tmp/film spiderman.ts
我想用我的C程序来控制它就像用echo函数
一样echo "pause" >> /tmp/film
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int fdes,res;
char x;
/*commands*/
char msg1[] = "pausen";
char msg2[] = "quitn";
/*creating fifo file*/
unlink("/tmp/film");
res=mknod("/tmp/film", S_IFIFO|0666, 0);
if (res<0) perror("error_creating_fifo");
fdes = open("/tmp/film", O_WRONLY);
if (fdes<0) perror("error_open_fifo");
while(1)
{
printf("Enter commandn");
x = getchar();
getchar();//dont take enter character
switch(x)
{
case 'p':
printf("PAUSEn");
write(fdes, msg1, sizeof(msg1));
break;
case 'q':
printf("QUITn");
write(fdes, msg2, sizeof(msg2));
break;
default:
printf("Unknown command");
break;
}
}
close(fdes);
return 0;
}
问题是,它只能工作一次。例如,我不能暂停然后再取消电影
为每个命令关闭和重新打开管道对我来说很有效:
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
char MPLAYER_CTRL[] = "/tmp/mplayer-control";
int startMPlayerInBackground()
{
pid_t processId = fork();
if (processId == 0)
{
printf("running mplayern");
char cmd[256];
snprintf(cmd, 256, "mplayer -quiet -fs -slave -idle -input file=%s", MPLAYER_CTRL);
int status = system(cmd);
printf("mplayer ended with status %dn", status);
exit(status);
}
else
{
return processId;
}
}
void send(char* cmd)
{
int fdes = open(MPLAYER_CTRL, O_WRONLY);
write(fdes, cmd, strlen(cmd));
close(fdes);
}
int main(int argc, char *args[])
{
unlink(MPLAYER_CTRL);
int res = mknod(MPLAYER_CTRL, S_IFIFO|0777, 0);
pid_t processId = startMPlayerInBackground();
if (processId < 0)
{
printf("failed to start child processn");
}
else
{
send("loadfile /home/duo/ninja.mp3n");
sleep(2);
send("pausen");
sleep(1);
send("pausen");
sleep(2);
send("quitn");
}
return 0;
}