Search code examples
cffmpegsystem-callsterminate

Terminating a c function


I want to make a function in c, that will capture video under Linux. I embedded ffmpeg command via system() in my c program, which captures video. ffmpeg terminates by pressing [q]. How can I include termination into my c program.

This function is part of a server.c program. When client requests for termination, I want video cature function to terminate. Is this possible?

#include<stdio.h>
#include <string.h>


main()
{

char command[180];

sprintf(command, "ffmpeg -f v4l2 -r 25 -s 640x480 -i /dev/video0 out.avi");
system(command);

}

Solution

  • As you asked sample for fork, exec, kill here is possible solution. avconv is replacement for ffmpeg on my pc.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <signal.h>
    #include <errno.h>
    #include <assert.h>
    #include <unistd.h>
    #include <sched.h>
    #include <sys/wait.h>
    
    pid_t parent_pid;
    
    void sigquit_handler (int sig)
    {
        assert(sig == SIGKILL);
        pid_t self = getpid();
        if (parent_pid != self)
        {
            printf("recording done");
            _exit(0);
        }
    }
    
    int main()
    {
        int pid = 0;
        int status;
        pid_t child;
    
        signal(SIGKILL, sigquit_handler);
        parent_pid = getpid();
    
        pid = fork();
    
        if ( pid == 0)
        {
            execl("/usr/bin/avconv","avconv","-f","video4linux2","-r","25","-s","640x480","-i","/dev/video0","out.avi",(char*)0);
        }
        else if( pid > 0)
        {
            sleep(5);
            kill(pid, SIGKILL);
    
            child = wait(&status);
            printf("child %d succesully quit\n", (int)child);
        }
        return 0;
    }