0% found this document useful (0 votes)
143 views27 pages

Final OS Lab Print

A shell script accepts a file name and starting and ending line numbers as arguments, and displays the lines between those line numbers from the given file. Another shell script deletes all lines containing a specified word from one or more supplied files. A third shell script displays files in the current directory that the user has read, write and execute permissions for.

Uploaded by

kamalteja
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views27 pages

Final OS Lab Print

A shell script accepts a file name and starting and ending line numbers as arguments, and displays the lines between those line numbers from the given file. Another shell script deletes all lines containing a specified word from one or more supplied files. A third shell script displays files in the current directory that the user has read, write and execute permissions for.

Uploaded by

kamalteja
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1 ) Write a shell script that accepts a file name, starting and ending line numbers as arguments and display

all the lines between the given line numbers. echo "enter file name" read f echo 'enter starting position' read st echo 'enter ending position' read end echo 'The lines between' $st 'and' $end 'from' $f if [ $st -lt $end ] then n1=`expr $st + 1` n2=`expr $end - 1` sed -n "$n1,$n2 p" $f elif [ $st -gt $end ] then n3=`expr $st - 1` n4=`expr $end + 1` sed -n "$n4,$n3 p" $f fi Output: $ sh first.sh enter file name fname enter starting position 1 enter ending position 4 The lines between 1 and 4 from fname hello world hello sri 2) Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. echo 'enter a word to be deleted' read word echo 'enter file name' read fname echo 'lines in' $fname 'after deleting the word' $word ':' sed "/$word/d" $fname Output: $ sh del.sh enter a word to be deleted hello

enter file name sample.sh lines in sample.sh after deleting the word hello : hi..... end of the text..... [s11031d0519@www os]$ vi sample.sh hi..... hello world hello sit... hello user... end of the text..... 3) Write a shell script that displays a list of all the files in the current directory to which the user has read, write and execute permissions. for i in * do if [ -r $i -a -w $i -a -x $i ] then echo $i fi done Output: $ sh rwper.sh a.out fname list.sh new shell. 4)Write a shell script that receives any number of file names as arguments checks if every argument supplied is a file or directory and reports accordingly. whenever the argument is a file, the number of lines on it is also reported. for fname in $* do if [ -f $fname ] then echo $fname 'is a file' echo 'no.of lines in' $fname ':' wc -l $fname elif [ -d $fname ] then echo $fname 'is a directory' else echo 'Does not exist' fi done

Output: $ sh filedir.sh fname fname is a file no.of lines in fname : 5 fname $ sh filedir.sh fname a.out shell fname is a file no.of lines in fname : 5 fname a.out is a file no.of lines in a.out : 14 a.out shell is a directory 5) Write a shell script that accepts a file names as its arguments, counts and reports the occurrence of each word that is present in the file argument file in other argument files. if [ $# -eq 0 ] then echo "no arguments" else tr " " "\n" < $1 > temp shift for i in $* do tr " " "\n" < $i > temp1 y=`wc -l < temp` j=1 while [ $j -le $y ] do x=`head -n $j temp | tail -1` c=`grep -c "$x" temp1` echo $x $c j=`expr $j + 1` done done fi Output: $ sh 5.sh fname sample.sh hello.... 0 hello 3 world 1 hello 3 sri 0 end 1 of 1 the 1 text 1 3

hdgs 0 krfplqw 0

6) Write a shell script to all of the directory files in a directory. enter a directory name echo 'enter a directory name' read dname echo 'The list of directory files in the directory' $dname 'are' cd $dname ls -l | grep '^d' Output: $ sh list.sh os The list of directory files in the directory os are list.sh: cd: os: No such file or directory drwxr-xr-x 3 s11031d0 cs11 4096 Mar 22 11:04 new drwxr-xr-x 3 s11031d0 cs11 4096 Mar 22 11:07 shell 7)Write a shell script to find factorial of a given number. echo 'enter a number' read n i=1 fact=1 while [ $i -le $n ] do fact=`expr $fact \* $i` i=`expr $i + 1` done echo 'The factorial of' $n 'is' $fact Output: $ sh fact.sh enter a number 5 The factorial of 5 is 120 8)Write a awk script to count the number of lines in a file that do not contain vowels. echo 'enter a file name' read fn awk '$0 !~/[aeiou]/ { c=c+1 } END { print("The no.of lines that do not contain vowels:",c) }' $fn

Output: $ sh lcount.awk enter a file name fname The no.of lines that do not contain vowels: 1 9) Write a awk script to find the number of characters,words and lines in a file. echo "enter a file name" read fn awk '{ w=w+NF c=c+length($0) } END { print("No.of lines:",NR) print("No.of words:",w) print("No.of characters:",c) }' $fn Output: $ sh cwlcount.awk enter a file name sample.sh No.of lines: 5 No.of words: 11 No.of characters: 63 10) Write a C program that makes a copy of a file using standard I/O and system calls. #include<stdio.h> #include<fcntl.h> #define MAX_SIZE 1000 main() { int fd1,fd2,r1,w1; char buffer[MAX_SIZE]; char sourceName[100],destName[100]; printf("enter the source file\n"); scanf("%s",sourceName); printf("enter a new file name"); scanf("%s",destName); fd1=open(sourceName,O_RDONLY);

r1=read(fd1,buffer,MAX_SIZE); fd2=open(destName,O_CREAT|O_RDWR,0600); w1=write(fd2,buffer,r1); } Output: $ cc 10.c $ ./a.out enter the source file fname enter a new file name newfile $ vi fname hello.... hello world hello sit end of the text

$vi newfile hello....x hello world hello sit end of the text

11)Implement in C the following Unix commands using system calls. a) cat command #include<fcntl.h> #define MAX_SIZE 500 main() { int fd1,n; char buf[MAX_SIZE],fname[20]; printf("enter a file name\n"); scanf("%s",fname); fd1=open(fname,O_RDONLY); if(fd1==-1) printf("the file does not exist"); else { printf("The contents of file %s are:\n",fname); n=read(fd1,buf,MAX_SIZE); write(1,buf,n); } } Output: $ cc CatCommand11a.c $ ./a.out enter a file name sample.sh The contents of file sample.sh are: 6

hi..... hello world hello sit... hello user... end of the text.....

11b)mv command #include<fcntl.h> #include<sys/stat.h> main(int argc,char *argv[]) { open(argv[1],O_RDONLY); creat(argv[2],S_IWUSR); rename(argv[1],argv[2]); unlink(argv[1]); } Output: $ cc MvPgm11b.c $ ./a.out sample.sh sample $ cat sample.sh cat: sample.sh: No such file or directory $ cat sample hi..... hello world hello sit... hello user... end of the text..... 12) Write a C program to list directory files in directory. #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<dirent.h> main() { struct stat buf; struct dirent *direntp; DIR *dirp; char dirName[40],name[40]; printf("enter directory name\n"); scanf("%s",&dirName); dirp=opendir(dirName); while((direntp=readdir(dirp))!=NULL) { stat(direntp->d_name,&buf); 7

if(S_ISDIR(buf.st_mode)) printf("%s\n",direntp->d_name); } } Output: $ cc ListOfDirFiles12.c $ ./a.out enter directory name new . .. new1 sri 13) Write a C program to emulate the unix ls l command. #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<dirent.h> #include<time.h> #include<pwd.h> #include<grp.h> #include<stdint.h> #include<string.h> int main() { char* getuser(int uid,char* s); char* getperms(int mode,char* s); char* getgroup(int gid,char* s); int cscmp(const void *a, const void *b); struct dirent *d; struct stat st; struct tm *tm; DIR *p; int i=0,j=0,bcount=0; char datestring[17],pstring[10],ustring[20],gstring[20]; char cwd[1024]; char *fnames[1024]; getcwd(cwd,sizeof(cwd)); p=opendir(cwd); while(d=readdir(p)) { if(d->d_name[0]!= '.') { 8

lstat(d->d_name,&st); fnames[i++]=d->d_name; bcount=bcount+st.st_blocks/2; } } qsort(fnames,i,4,cscmp); printf("total %d\n",bcount); while(j<i) { lstat(fnames[j], &st); tm=localtime(&st.st_mtime); strftime(datestring,17,"%Y-%m-%d %H:%M",tm); getperms(st.st_mode,pstring); getuser(st.st_uid,ustring); getgroup(st.st_gid,gstring); printf("%s %4d %s %s",pstring,st.st_nlink,ustring,gstring); printf("%9jd %s %s \n",(intmax_t)st.st_size,datestring,fnames[j++]); } return 0; } char* getperms(int mode,char* s) { mode_t owner, group, other; if(S_ISREG(mode)) *s++ = '-'; else if(S_ISDIR(mode)) *s++ = 'd'; else if(S_ISCHR(mode)) *s++ = 'c'; else if(S_ISBLK(mode)) *s++ = 'b'; else if(S_ISFIFO(mode)) *s++ = 'f'; else if(S_ISLNK(mode)) *s++ = 'l'; else *s++ = 's'; owner = mode & S_IRWXU; group = mode & S_IRWXG; other = mode & S_IRWXO; *s++ = owner & S_IRUSR ? 'r' : '-'; *s++ = owner & S_IWUSR ? 'w' : '-'; *s++ = owner & S_IXUSR ? 'x' : '-'; *s++ = group & S_IRGRP ? 'r' : '-'; *s++ = group & S_IWGRP ? 'w' : '-'; *s++ = group & S_IXGRP ? 'x' : '-'; *s++ = other & S_IROTH ? 'r' : '-'; *s++ = other & S_IWOTH ? 'w' : '-'; 9

*s++ = other & S_IXOTH ? 'x' : '-'; *s = '\0'; return s; } char* getuser(int uid,char* s) { struct passwd *pwd; if ((pwd = getpwuid(uid)) != NULL) strcpy(s,pwd->pw_name); else snprintf(s,20,"%d",uid); return s; } char* getgroup(int gid,char* s) { struct group *grp; if ((grp = getgrgid(gid)) != NULL) strcpy(s,grp->gr_name); else snprintf(s,20,"%d",gid); return s; } int cscmp(const void *a, const void *b) { const char **ia = (const char **)a; const char **ib = (const char **)b; return strcasecmp(*ia, *ib); } Output: $cc 13.c $./a.out total 20 -rwxr-xr-x -rw-r--r--rw-r--r--rw-r--r--

1 user group 7756 2012-05-02 19:57 a.out 1 user group 2605 2012-05-02 19:56 13.c 1 user group 284 2012-05-01 11:03 A.c 1 user group 275 2012-05-01 11:03 B.c

14) Write a C program to list for every file in a directory, its inode number in a given directory #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<dirent.h> main() { struct stat buf; 10

struct dirent *direntp; DIR *dirp; char dirName[40],name[40]; printf("enter directory name\n"); scanf("%s",&dirName); chdir(dirName); dirp=opendir(dirName); while((direntp=readdir(dirp))!=NULL) { stat(direntp->d_name,&buf); printf("%d %s",buf.st_ino,direntp->d_name); printf("\n"); } } Output: $ cc 14.c $ ./a.out Enter Directory Name new 10748078 . 11813612 .. 11813612 new1 11813612 sri 11813612 core.9696 15) Write a C program that redirects standard output to a file. #include<stdio.h> #include<fcntl.h> main(int argc,char **argv) { int fd; if(argc!=3) { printf("please provide necessary arguments"); exit(1); } fd=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC); if(fd==-1) { printf("failed to open a file"); exit(1); } dup2(fd,1); execlp(argv[1],argv[1],NULL); }

11

Output: $ cc redirect15.c $ ./a.out pwd f1 $ cat f1 /home/os 16) Write a C program to create a child process and allow the parent to display parent and the child to display child on the screen. #include<stdio.h> #include<fcntl.h> main() { pid_t pid; pid=fork(); if(pid==-1) printf("failed to fork");

else if(pid==0) printf("child process:%d\n",getpid()); else printf("parent process:%d",getpid()); } Output: $ ./a.out parent process:10210 $ child process:10211 $ ./a.out parent process:10222 $ child process:10223 17) Write a C program to create a Zombie process #include<stdio.h> main() { int pid; pid=fork(); if(0==pid) { printf("child process %d \n",getpid()); _exit(0); }

12

else { wait(0); sleep(10); printf("parent process \n"); } } Output: $ cc ZombieProcess.c $ ./a.out child process 10365 (Note:After 10 sec Child Process is killed,parent process is continuing,,.) parent process 18) Write a C program that illustrates how an orphan is created. i) Orphan process #include<stdio.h> main() { int pid; pid=fork(); if(pid==0) { printf("I am the child process with PID:%d and my parent id is:%d\n\n",getpid(),getppid()); sleep(15); printf("I am the child process with PID:%d and my parent id is:%d\n",getpid(),getppid()); } else { printf("I am the parent process with PID:%d\n \n",getpid()); printf("My child's PID is:%d\n\n",pid); sleep(1); } printf("PID %d terminates \n",getpid()); /*Both processes execute this*/} Output: $ cc orphan18.c $ ./a.out I am the parent process with PID:10503 My child's PID is:10504 I am the child process with PID:10504 and my parent id is:10503 13

PID 10503 terminates $ I am the child process with PID:10504 and my parent id is:1 PID 10504 terminates 19) Write a C program that illustrates how to executing two commands concurrently with a command pipe. #include<stdio.h> main(int argc,char **argv) { int pid,fd[2],p; if(argc!=3) { printf("insufficient arguments"); exit(1); } p=pipe(fd); if(p==-1) { printf("pipe creation failed"); exit(1); } pid=fork(); if(pid==-1) { printf("fork failed"); exit(1); } if(pid==0) { close(fd[0]); dup2(fd[1],1); close(fd[1]); execlp(argv[1],argv[1],NULL); } else { close(fd[1]); dup2(fd[0],0); close(fd[0]); execlp(argv[2],argv[2],NULL); } } Output: $ cc pipetwocommandsexec19.c $ ./a.out insufficient arguments. 14

$ ./a.out cat|sort sample end of the text..... hello sit... hello user... hello world hi.....

20) Write a C program that illustrates communication between two unrelated process using named pipe. Program1: #include<stdio.h> #include<fcntl.h> main() { char *msg="hai"; int fd,pfd; pfd=mkfifo("pipe1",0666); if(pfd==-1) { printf("error creating the named pipe"); exit(1); } fd=open("pipe1",O_WRONLY); if(fd==-1) { printf("failed to open a pipe"); exit(1); } write(fd,msg,4); unlink("pipe1"); } Program2: #include<stdio.h> #include<fcntl.h> main() { char msg[10]; int fd,n; fd=open("pipe1",O_RDONLY); if(fd==-1) { printf("failed to open pipe"); exit(1); } 15

n=read(fd,msg,10); printf("message: %s\n",msg); } Output: $ cc 20a.c -o a $ cc 20b.c -o b $ ./a & [1] 5862 $ ./b message: hai 21)write a C program in which a parent writes a message to a pipe and the child reads the message. #include<stdio.h> main(){ int p[2],pid;char *buf; buf=(char *) malloc(10); pipe(p); pid=fork(); if(pid>0){printf("parent is writing on pipe\n"); write(p[1],"hello",5); } else { read(p[0],buf,5); printf("child is reading %s \n",buf);} close(p[0]);close(p[1]); } Output: $ cc ReadWritePipe21.c $ ./a.out parent is writing on pipe $ child is reading hello. 22)Write C program to transfer large amount of data between processes using a)Pipe: #include<stdio.h> #include<fcntl.h> main() { int p[2],pid,i,j;

16

char *buf,s[30],*src="10"; buf=malloc(30); pipe(p); pid=fork(); srand(47); for(i=0;i<10;i++) { if(pid>0) { for (j = 0; j < 30; j++) { s[j] = src[rand()%2]; } printf("Writing data to pipe : %s\n",s); write(p[1],s,30); } else { read(p[0],buf,30); printf("Recieving data from pipe : %s \n\n",buf); } sleep(1); } close(p[0]); close(p[1]); } Output: $cc 21a.c $./a.out Writing data to pipe : 100011110000100001111011001011 Recieving data from pipe : 100011110000100001111011001011 b)FIFO: #include<stdio.h> #include<fcntl.h> main() { int pid,i,j,fd; char *buf,s[30],*src="10"; buf=malloc(30); fd=mkfifo("myfifo",0666); pid=fork(); srand(57); for(i=0;i<10;i++) { if(pid>0) { for (j = 0; j < 30; j++) { 17

s[j] = src[rand()%2]; } fd=open("myfifo",O_WRONLY); printf("Writing data to FIFO : %s\n",s); write(fd,s,30); } else { fd=open("myfifo",O_RDONLY); read(fd,buf,30); printf("Recieving data from FIFO : %s \n\n",buf); } sleep(1); } unlink("myfifo"); }

Output: $cc 21b.c $./a.out Writing data to FIFO : 101101110101010111000000100110 Recieving data from FIFO : 101101110101010111000000100110 c)Message queue: #include<stdio.h> #include<fcntl.h> #include<sys/ipc.h> #include<sys/msg.h> main() { int pid,i,j,msqid; char *buf,s[30],*src="10"; buf=malloc(30); msqid=msgget((key_t)7,IPC_CREAT|0666); pid=fork(); srand(67); for(i=0;i<10;i++) { if(pid>0) { for (j = 0; j < 30; j++) { s[j] = src[rand()%2]; } printf("Writing data to message queue : %s\n",s); 18

msgsnd(msqid,&s,30,0); } else { msgrcv(msqid,buf,30,0,0); printf("Recieving data from message queue : %s \n\n",buf); } sleep(1); } } Output: $cc 21c.c $./a.out Writing data to message queue : 000001010000001100100111011111 Recieving data from message queue : 000001010000001100100111011111 23)Write a C program that implements a producer-consumer system with two process(using semaphores). #include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<signal.h> void abc() { printf("bye bye from child\n"); exit(0); } void xyz() { printf("bye bye from parent\n"); exit(0); } main() { int semid; int pid; struct sembuf sop; semid=semget((key_t)29,1,IPC_CREAT|0666); if(-1==semid) { perror("semget:"); exit(1); } semctl(semid,0,SETVAL,6); printf("semid=%d\n",semid); pid=fork(); 19

if(0==pid) { sop.sem_num=0; sop.sem_op=-1; sop.sem_flg=0; signal(SIGALRM,abc); alarm(6); while(1) { semop(semid,&sop,1); printf("child%d\n",semctl(semid,0,GETVAL,0)); sleep(1); } } else { sleep(7); sop.sem_num=0; sop.sem_op=1; sop.sem_flg=0; signal(SIGALRM,xyz); alarm(6); while(1) { semop(semid,&sop,1); printf("parent%d\n",semctl(semid,0,GETVAL,0)); sleep(1);}}} Output: $ cc 27.c $ ./a.out semid=327684 child5 child4 child3 child2 child1 child0 bye bye from child parent1 parent2 parent3 parent4 parent5 parent6 bye bye from parent 24)Write client and server programs(using c) for interaction between server and client processes using Unix Domain Sockets.

20

a)unix domain sockets(interaction between server and client)(server) #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <stdio.h> #define NSTRS 3 /* no. of strings */ #define ADDRESS "mysocket" /* addr to connect */ /* * Strings we send to the client. */ char *strs[NSTRS] = { "This is the first string from the server.\n", "This is the second string from the server.\n", "This is the third string from the server.\n" }; main() { char c; FILE *fp; int fromlen; register int i, s, ns, len; struct sockaddr_un saun, fsaun; /* * Get a socket to work with. This socket will * be in the UNIX domain, and will be a * stream socket. */ if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("server: socket"); exit(1); } /* * Create the address we will be binding to. */ saun.sun_family = AF_UNIX; strcpy(saun.sun_path, ADDRESS); /* * Try to bind the address to the socket. We * unlink the name first so that the bind won't * fail. * * The third argument indicates the "length" of * the structure, not just the length of the * socket name. */ 21

unlink(ADDRESS); len = sizeof(saun.sun_family) + strlen(saun.sun_path); if (bind(s, &saun, len) < 0) { perror("server: bind"); exit(1); } /* * Listen on the socket. */ if (listen(s, 5) < 0) { perror("server: listen"); exit(1); } /* * Accept connections. When we accept one, ns * will be connected to the client. fsaun will * contain the address of the client. */ if ((ns = accept(s, &fsaun, &fromlen)) < 0) { perror("server: accept"); exit(1); } /* * We'll use stdio for reading the socket. */ fp = fdopen(ns, "r"); /* * First we send some strings to the client. */ for (i = 0; i < NSTRS; i++) send(ns, strs[i], strlen(strs[i]), 0); /* * Then we read some strings from the client and * print them out. */ for (i = 0; i < NSTRS; i++) { while ((c = fgetc(fp)) != EOF) { putchar(c); if (c == '\n') break; } } /* 22

* We can simply use close() to terminate the * connection, since we're done with both sides. */ close(s); exit(0); } Output: $ cc sockserver28a.c $ ./a.out This is the first string from the client. This is the second string from the client. This is the third string from the client. Client.c #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <stdio.h> #define NSTRS 3 /* no. of strings */ #define ADDRESS "mysocket" /* addr to connect */ /* * Strings we send to the server. */ char *strs[NSTRS] = { "This is the first string from the client.\n", "This is the second string from the client.\n", "This is the third string from the client.\n" }; main() { char c; FILE *fp; register int i, s, len; struct sockaddr_un saun; /* * Get a socket to work with. This socket will * be in the UNIX domain, and will be a * stream socket. */ if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("client: socket"); exit(1); }

23

/* * Create the address we will be connecting to. */ saun.sun_family = AF_UNIX; strcpy(saun.sun_path, ADDRESS); /* * Try to connect to the address. For this to * succeed, the server must already have bound * this address, and must have issued a listen() * request. * * The third argument indicates the "length" of * the structure, not just the length of the * socket name. */ len = sizeof(saun.sun_family) + strlen(saun.sun_path); if (connect(s, &saun, len) < 0) { perror("client: connect"); exit(1); } /* * We'll use stdio for reading * the socket. */ fp = fdopen(s, "r"); /* * First we read some strings from the server * and print them out. */ for (i = 0; i < NSTRS; i++) { while ((c = fgetc(fp)) != EOF) { putchar(c); if (c == '\n') break; } } /* * Now we send some strings to the server. */ for (i = 0; i < NSTRS; i++) send(s, strs[i], strlen(strs[i]), 0); /* * We can simply use close() to terminate the * connection, since we're done with both sides. 24

*/ close(s); exit(0); } Output: $ cc sockserver28b.c $ ./a.out This is the first string from the server. This is the second string from the server. This is the third string from the server. 25)Write a C program that illustrates two process communicating via shared memory. a)shared memory(client) #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #define SHMSZ 27 main() { char c; int shmid; key_t key; char *shm, *s; key = 5678; if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } printf("shmid=%d\n",shmid); /* * Now we attach the segment to our data space. */ if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } /* * Now put some things into the memory for the * other process to read. */ s = shm; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = NULL; 25

/* * Finally, we wait until the other process * changes the first character of our memory * to '*', indicating that it has read what * we put there. */ while (*shm != '*') sleep(1); exit(0); } Output: $ cc shared30a.c $ ./a.out Shared Memory Id:622598 ABCDEFGHIJKLMNOPQRSTUVWXYZ b)shared memory(server) #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #define SHMSZ 27 main() { int shmid; key_t key; char *shm, *s; /* * We need to get the segment named * "5678", created by the server. */ key = 5678; /* * Locate the segment. */ if ((shmid = shmget(key, SHMSZ, 0666)) < 0) { perror("shmget"); exit(1); } /* * Now we attach the segment to our data space. */

26

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } /* * Now read what the server put in the memory. */ for (s = shm; *s != NULL; s++) putchar(*s); putchar('\n'); /* * Finally, change the first character of the * segment to '*', indicating we have read * the segment. */ *shm = '*'; exit(0); } Output: $ cc shared30b.c $ ./a.out Shared Memory Id:622598 ABCDEFGHIJKLMNOPQRSTUVWXYZ

27

You might also like