Documentos de Académico
Documentos de Profesional
Documentos de Cultura
(lectures programs)
Part 1: UNIX File System
5
3
char *strings[] = {
"aaa", "bbb", "ccc", "ddd", "eee"
};
main ....
{
int fd;
fd = open ( fname, O_RDWR | O_CREAT | O_TRUNC, 0666
);
for (n = 0; n < NSTRINGS; n++)
write(fd, strings[n], STRSIZE);
/* user provides the value of n */
lseek ( fd, (n-1) * STRSIZE, SEEK_SET );
read ( fd, buf, STRSIZE );
write(1, buf, STRSIZE);
}
Exampl 4: lstat.c
main ...
{
char *filename;
struct stat st;
lstat (filename, &st);
outputStatInfo(filename, &st);
}
Example 5: listfiles.c
main ...
{
DIR *dp;
char *dirname;
struct stat st;
struct dirent *d;
dp = opendir(dirname);
while ((d = readdir(dp)) != NULL) {
sprintf(filename, "%s/%s", dirname, d>d_name);
lstat(filename, &st);
outputStatInfo(filename, d->d_name, &st);
}
}
Part 2: Signals
pause()
To wait for a signal
Example 6:
signal1.c
main ...
{
signal(SIGUSR1, handler);
signal(SIGUSR2, handler);
for (;;) pause();
}
handler(int sig)
{
/* Print out what we received */
psignal(sig, "Received signal");
}
Examples of usage:
% kill -l
HUP INT QUIT ILL TRAP ABRT EMT FPE KILL BUS SEGV
SYS PIPE ALRM TERM USR1 USR2
CLD PWR WINCH URG POLL STOP TSTP CONT TTIN TTOU
Part 3: Processes
Basic Concepts:
Process identifiers:
getpid(): to get the process id.
getppid(): to get the parent process id.
Create a new process:
fork(): to create a new child process.
Terminate:
}
pause();
}
pid = fork();
if (pid == 0) {
read(in, buf,
write(1, buf,
}
else {
read(in, buf,
write(1, buf,
}
write(1,"\n", 1);
3);
3);
3);
3);
if (pid == 0)
execl("./fileread", "fileread", 0);
else
execl("./fileread", "fileread", 0);
}
The program exec a file called: fileread.c
main()
{
char buf[1024];
read(3, buf, 3);
write(1, buf, 3);
write(1,"\n", 1);
}
Use:
% kill -INT <pid>
to send a INT signal to <pid>
Simple Shell:
Example 15: wsh.c
main()
{
int status;
pid_t pid;
char command[BUFSIZ];
for (;;) {
printf("wsh> ");
if (fgets(command, sizeof(command), stdin) ==
NULL) {
putchar('\n');
exit(0);
}
command[strlen(command)-1] = NULL;
if ((pid = fork()) == 0)
execlp(command, command, 0);
close(pfd[1]);
waitpid(pid, &status, 0);
exit(0);
}