我必须在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[] = "pause\n";
char msg2[] = "quit\n";
/*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 command\n");
x = getchar();
getchar();//dont take enter character
switch(x)
{
case 'p':
printf("PAUSE\n");
write(fdes, msg1, sizeof(msg1));
break;
case 'q':
printf("QUIT\n");
write(fdes, msg2, sizeof(msg2));
break;
default:
printf("Unknown command");
break;
}
}
close(fdes);
return 0;
}
问题是,它只能运作一次。我不能暂停,然后取消暂停电影。
答案 0 :(得分: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 mplayer\n");
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 %d\n", 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 process\n");
}
else
{
send("loadfile /home/duo/ninja.mp3\n");
sleep(2);
send("pause\n");
sleep(1);
send("pause\n");
sleep(2);
send("quit\n");
}
return 0;
}