16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

C Libraries<br />

/* readdir: read directory entries in sequence */<br />

#include /* local directory structure */<br />

Dirent *readdir(DIR *dp)<br />

{<br />

struct direct dirbuf; /* local directory structure */<br />

static Dirent d; /* return: portable structure */<br />

}<br />

while(read(dp->fd,(char*) &dirbuf, sizeof(dirbuf))== sizeof(dirbuf))<br />

{<br />

if (dirbuf.d_ino == 0) /* slot not in use */<br />

continue;<br />

d.ino = dirbuf.d_ino;<br />

strncpy(d.name, dirbuf.d_name, DIRSIZ);<br />

d.name[DIRSIZ] = '\0'; /* ensure termination */<br />

return &d;<br />

}<br />

return NULL;<br />

File Status and Control<br />

int fstat(int fd, struct stat *status);<br />

int link(char *origfile, char *newfile);<br />

int chmod(char *filename, int accessmode);<br />

int chdir(char *dirname); /* return 0 if successful */<br />

int ioctl(int fd, int request, struct req *reqparams);<br />

/* get and set line parameters (baud rate etc) */<br />

System call I/O<br />

User<br />

function calls<br />

values<br />

Standard I/O<br />

return<br />

function calls Standard call return values<br />

function calls UNIX kernel return values<br />

Pipes<br />

FILE *p; /* pipe stream */<br />

char line[MAXLINE]; /* lines read */<br />

if ((p = popen("grep unix *","r")) == NULL){<br />

fprintf(stderr,"can't create pipe\n"); exit(1);<br />

}<br />

while (fgets(line,sizeof line, p) != EOF){<br />

/* do something <strong>with</strong> line */<br />

}<br />

pclose(p); /* close <strong>the</strong> pipe */<br />

Parallel execution<br />

fork duplicates a process and sets both executing in parallel, where as exec allows process to hand over control to<br />

ano<strong>the</strong>r program. By combining fork and exec, one program may start a second program and continue executing<br />

itself. The original is <strong>the</strong>n called <strong>the</strong> parent process, <strong>the</strong> copy is called <strong>the</strong> child process and both exe in parallel.<br />

system(char *command) /* execute a shell command*/<br />

{<br />

int status; /* status returned by command */<br />

int pid; /* process id of command */<br />

int wval; /* value returned by wait */<br />

73

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!