應用與MPlayer通過slave模式進行信息交換
代碼如下
編譯方法
gcc test.c -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
/**********************全局變量定義區*****************/
int fd_fifo; //創建有名管道,用於向mplayer發送命令
int fd_pipe[2]; //創建無名管道,用於從mplayer讀取命令
void *get_pthread (void *arg)
{
char buf[100];
while (1)
{
printf ("please input you cmd:");
fflush (stdout);
fgets (buf, sizeof (buf), stdin); //從標準輸入獲取數據
buf[strlen (buf)] = '\0';
printf ("*%s*\n", buf);
if (write (fd_fifo, buf, strlen (buf)) != strlen (buf))
perror ("write"); //將命令寫入命名管道
}
}
void *print_pthread (void *arg)
{
char buf[100];
close (fd_pipe[1]);
int size = 0;
while (1)
{
size = read (fd_pipe[0], buf, sizeof (buf)); //從無名管道的寫端讀取信息打印在屏幕上
buf[size] = '\0';
printf ("th msg read form pipe is %s\n", buf);
}
}
int main (int argc, char *argv[])
{
int fd;
char buf[100];
pid_t pid;
unlink ("/tmp/my_fifo"); //如果明明管道存在,則先刪除
mkfifo ("/tmp/my_fifo", O_CREAT | 0666);
perror ("mkfifo");
if (pipe (fd_pipe) < 0) //創建無名管道
{
perror ("pipe error\n");
exit (-1);
}
pid = fork ();
if (pid < 0)
{
perror ("fork");
}
if (pid == 0) //子進程播放mplayer
{
close (fd_pipe[0]);
dup2 (fd_pipe[1], 1); //將子進程的標準輸出重定向到管道的寫端
fd_fifo = open ("/tmp/my_fifo", O_RDWR);
execlp ("mplayer", "mplayer", "-slave", "-quiet", "-loop", "0", "-input", "file=/tmp/my_fifo", "/home/user/Downloads/text2audio.mp3", NULL);
}
else
{
pthread_t tid1;
pthread_t tid2;
fd_fifo = open ("/tmp/my_fifo", O_RDWR);
if (fd < 0)
perror ("open");
pthread_create (&tid1, NULL, get_pthread, NULL); //從鍵盤獲取控制信息
pthread_create (&tid2, NULL, print_pthread, NULL); //打印從無名管道收到的信息
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
}
return 0;
}