システムコールreadを使った簡単なプログラミング


/* simple_read.c*/
#include<unistd.h> /* read, write */
#include<stdlib.h> /* exit */
int main()
{
/*
#include <unistd.h>
  size_t read(int fildes, void *buf, size_t nbytes);

#include <unistd.h>
  size_t write(int fildes, const void *buf, size_t nbytes);

#include <stdlib.h>
  void exit(int status);
*/

/*When a program starts, it usually has three of these descriptor
 already opened. 1:Standard input, 2:Standard output, 3:Standard error
 */
char buffer[128];
int nread;
/*copies the first 128 bytes of the standard input to the standard output. It copies
  all of the input if there are less than 128 bytes.*/
nread = read(0,buffer, 128);
if(nread == -1)
write(2, "A read error has occurred\n", 26);
if((write(1,buffer,nread)) != nread)
write(2, "A write error has occurred\n", 27);

/* When a program exits, all open file descriptors are automatically closed,
 so we don't need to close them explicitly */
exit(0);
}

#以下実行例
$ gcc -o simple_read simple_read.c


$ ./simple_read
Hello goodbye
Hello goodbye



$ echo "Hello, goodbye" | ./simple_read
Hello, goodbye