2012/11/27

Linux Pipeline Sample

Sample code shows how to use pipelin on Linux:

pid_t pid = 0; int pipefd[2]; pipe(pipefd); pid = fork(); if( -1 == pid ){ std::cerr << "Fork failed;" << std::endl; } else if( 0 == pid ){ int ret = 0; // Child process, will start ffmpeg to get meta data info close(pipefd[0]); // not care about pipe read end. dup2(pipefd[1], 1); // redirect the stdout to pipe write end dup2(pipefd[1], 2); // redirect the stderr to pipe write end close(pipefd[1]); ret = execlp("ffmpeg","ffmpeg", "-i", filePath.c_str() , NULL); exit(126); }else { // Parent process char buffer[4096]; // not care about the pipe write end; // if we do not close it, the child pipe will not close fully. close(pipefd[1]); FILE * pipeFile = NULL; int shouldPrint = 0; pipeFile = fdopen( pipefd[0], "r"); // read from pipe read end. // Wait a while, another option is to use wait pid sleep(1); while(1) { char * p1; char * p2; p1 = fgets( buffer, 4096, pipeFile ); if(p1 == NULL){ break; } if( shouldPrint == 0){ p2 = strstr(p1, "Metadata"); if(p2){ shouldPrint = 1; } } else{ p2 = strstr(p1, "Duration"); if(p2){ break; } std::cout << p1; } } fclose(pipeFile); } }

Post Code on Blogger

Simplest way to post code to blogger for me: <pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black;overflow-x:...