天天看點

指令行音樂播放器代碼

 最近想在linux平台下寫一款音樂播放器,找了一下,沒有其他的解決辦法,于是想調用mmplayer的代碼來達到播放音樂的目的,然後開始寫了之後,發現需要用的技術還挺多的。包括,多線程程式設計,多程序程式設計,程序間通訊,線程間通訊,條件變量,互斥量,線程鎖,有名管道以及無名管道,權當複習一下linux系統調用程式設計,下面我把代碼複制到下面,大家參考一下,相關的資料在網上都能找得到。

#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輸出的消息

//發送到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));

        if (size == 0) {

            return 1;

        }

        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");

    if( mkfifo("/tmp/my_fifo",O_CREAT|0666) < 0)

    {

        perror("mkfifo");

    }

    if(pipe(fd_pipe) < 0)

    {

        perror("pipe");

        exit(-1);

    }

    pid = fork();

    if(pid < 0)

    {

        perror("fork");

        exit(-1);

    }

char buf[10];

atoi()

if(pid == 0)  //子程序

    {

        close(fd_pipe[0]);

        dup2(fd_pipe[1],1);

        if(fd_fifo = open("/tmp/my_fifo",O_RDWR) < 0)

        {   

            perror("son fd_fifo");

        }

        execlp("mplayer","mplayer","-slave","-quiet","-input",\

        "file=/tmp/my_fifo","ge.wav","-loop","0",NULL);

    }

    else

    {

        pthread_t tid1;

        pthread_t tid2;

        fd_fifo=open("/tmp/my_fifo",O_RDWR);

        if(fd_fifo<0)

        {

            perror("open my_fifo");

        }

        pthread_create(&tid1,NULL,get_pthread,NULL);

        pthread_create(&tid2,NULL,print_pthread,NULL);

        pthread_join(tid1,NULL);   //等待線程結束

        pthread_join(tid2,NULL);

    }

    return 0;

}

繼續閱讀