1. 读取当前目录下所有的文件名
#include <stdio.h>
#include <dirent.h>
int main( int argc, char *argv[] )
{
DIR *dp;
struct dirent *dirp;
if ( argc != 2 )
printf("usage: ls directory_name" );
if ( ( dp = opendir( argv[ 1 ] ) ) == NULL )
printf( "can't open %s\n", argv[ 1 ] );
while ( ( dirp = readdir( dp ) ) != NULL )
printf("%s***", dirp->d_name );
closedir( dp );
exit( 0 );
}
程序输出:
2. 将输入写到输出中
#include <unistd.h>
#include <stdio.h>
#define BUFSIZE 4096
int main( void )
{
int n;
char buf[ BUFSIZE ];
while ( ( n = read( STDIN_FILENO, buf, BUFFSIZE ) ) > 0 )
if ( write( STDOUT_FILENO, buf, n ) != n )
printf( "write error" );
if ( n < 0 )
printf( "read error" );
exit( 0 );
}
程序输出:
当然,如下代码的功能一样:
#include <stdio.h>
int main( void )
{
int c;
while ( ( c = getc( stdin ) ) != EOF )
if ( putc( c, stdout ) == EOF )
printf( "output error" );
if ( ferror( stdin ) )
printf( "input error" );
return 0;
}
3. 关于进程的程序
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXLINE 4096
int main( void )
{
char buf[ MAXLINE ];
pid_t pid;
int status;
printf( "%% " );
while ( fgets( buf, MAXLINE, stdin ) != NULL ){
if ( buf[ strlen( buf ) - 1 ] == '\n' )
buf[ strlen( buf ) - 1 ] = '\0';
if ( ( pid = fork() ) < 0 ){
printf( "fork error" );
}else if ( pid == 0 ){
execlp( buf, buf, ( char * )0 );
printf( "couldn't execute:%s", buf );
exit( 127 );
}
if ( ( pid = waitpid( pid, &status, 0 ) ) < 0 )
printf( "waitpid error" );
printf( "%% " );
}
return 0;
}
程序输出:
1) fork创建一新进程。fork向父进程返回新子进程的进程ID(非负),对子进程则返回0(所以fork被调用一次,返回两次)
2) execlp执行从标准输入读取的命令,而父进程通过waitpid来等待子进程的结束。
3) 最后执行ctrl+d来结束程序
4. 关于信号
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXLINE 4096
static void sig_int( int );
int main( void )
{
char buf[ MAXLINE ];
pid_t pid;
int status;
if ( signal( SIGINT, sig_int ) == SIG_ERR )
printf( "signal error" );
printf( "%% " );
while ( fgets( buf, MAXLINE, stdin ) != NULL ){
if ( buf[ strlen( buf ) - 1 ] == '\n' )
buf[ strlen( buf ) - 1 ] = '\0';
if ( ( pid = fork() ) < 0 ){
printf( "fork error" );
}else if ( pid == 0 ){
execlp( buf, buf, ( char * )0 );
printf( "couldn't execute:%s", buf );
exit( 127 );
}
if ( ( pid = waitpid( pid, &status, 0 ) ) < 0 )
printf( "waitpid error" );
printf( "%% " );
}
return 0;
}
void sig_int( int signo )
{
printf("interrupt\n");
}
这里捕捉中断信号ctrl+c。如果我们执行ctrl+c,则会打印信息: