# Modified by Rockie Cheng based on a common online test program
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <assert. h>
# Include <getopt. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <errno. h>
# Include <malloc. h>
# Include <sys/STAT. h>
# Include <sys/types. h>
# Include <sys/time. h>
# Include <sys/Mman. h>
# Include <sys/IOCTL. h>
# Include <ASM/types. h>
# Include <Linux/videodev2.h>
# Define clear (x) memset (& (x), 0, sizeof (x ))
Struct buffer {
Void * start;
Size_t length;
};
Static char * dev_name = "/dev/video0 ";
Static int FD =-1;
Struct buffer * buffers = NULL;
File * file_fd;
Static unsigned long file_length;
Static unsigned char * file_name;
Int main (INT argc, char ** argv)
{
Struct v4l2_capability cap;
Struct v4l2_format FMT;
File_fd = fopen ("test.jpg", "W ");
FD = open (dev_name, o_rdwr/* required */| o_nonblock, 0 );
IOCTL (FD, vidioc_querycap, & Cap );
Clear (FMT );
FMT. type = v4l2_buf_type_video_capture;
FMT. FMT. pix. width = 640;
FMT. FMT. pix. Height = 480;
FMT. FMT. pix. pixelformat = v4l2_pix_fmt_yuyv;
FMT. FMT. pix. Field = v4l2_field_interlaced;
IOCTL (FD, vidioc_s_fmt, & FMT );
File_length = FMT. FMT. pix. bytesperline * FMT. FMT. pix. height;
Buffers = calloc (1, sizeof (* buffers ));
Buffers [0]. Length = file_length;
Buffers [0]. Start = malloc (file_length );
For (;;)
{
Fd_set FDS;
Struct timeval TV;
Int R;
Fd_zero (& FDs );
Fd_set (FD, & FDs );
/* Timeout .*/
TV. TV _sec = 3;
TV. TV _usec = 0;
R = select (FD + 1, & FDS, null, null, & TV );
If (-1 = r ){
If (eintr = errno)
Continue;
Printf ("select ");
}
If (0 = r ){
Fprintf (stderr, "select timeout \ n ");
Exit (exit_failure );
}
If (read (FD, buffers [0]. Start, buffers [0]. Length ))
Break;
}
Fwrite (buffers [0]. Start, buffers [0]. length, 1, file_fd );
Free (buffers [0]. Start );
Close (FD );
Fclose (file_fd );
Exit (exit_success );
Return 0;
}
This article from the Linux community website (www.linuxidc.com) original link: http://www.linuxidc.com/Linux/2011-03/33021.htm