2

我必须在 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;
}

问题是,它只工作一次。例如,我不能暂停然后取消暂停电影。

4

1 回答 1

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;
}
于 2018-08-27T16:09:53.197 回答