np lab record

Upload: nag-raj

Post on 03-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 NP Lab Record

    1/151

    1. Write a shell script that accepts a file name, starting and ending linenumbers as arguments and displays all the lines between the given line

    numbers.

    echo 'enter a filename'

    read fname

    echo 'enter starting line number'

    read stecho 'enter ending line number'

    read eno

    echo 'the lines between '$st 'and' $eno 'from' $fname

    sed -n "$st,$eno p" $fname

    2. Write a shell script that deletes all lines containing a specified word inone or more files supplied as arguments to it.

    if [ $# -eq 0 ]

    thenecho "no arguments"

    else

    echo "enter a deleting word or char"

    read y

    for i in $*

    do

    grep -v "$y" "$i" > temp

    if [ $? -ne 0 ]

    thenecho "pattern not found"

    else

    cp temp $i

    rm temp

    fi

    done

    fi

    3. Write a shell script that displays a list of all the files in the currentdirectory to which the user has read, write and execute permissions.pwd

    for i in `ls`

    do

    if [ -r $i -a -w $i -a -x $i ]

    then

    echo "$i has all permissions"

    ls -l $i

    fidone

  • 7/29/2019 NP Lab Record

    2/152

    4. Write a shell script that receives any number of filenames asarguments checks if every argument supplied is a file or a 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

    5. Write a shell script that accepts a list of file names as its arguments,counts and reportsthe occurrence of each word that is present in the first

    argument file on other argument files.

    if [ $# -eq 0 ]

    then

    echo "no arguments"

    elsetr " " "\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

    6. Write a shell script to list all of the directory files in a directory.echo 'enter a directory name'

    read name

    echo 'The list of files in the directory' $name 'are'

    ls -l $dname>file

    grep '^d' file

  • 7/29/2019 NP Lab Record

    3/153

    7. Write a shell script to find factorial of a given integer.echo 'enter a number'

    read n

    i=1

    fact=1

    while [ $i -le $n ]

    dofact=`expr $fact \* $i`

    i=`expr $i + 1`

    done

    echo 'The factorial of' $n 'is' $fact

    8. Write an awk script to count the number of lines in a file that do notcontain vowels.

    echo "enter a file name"

    readfnawk '$0 !~/[aeiou]/ {c=c+1}

    END {print("the no. of lines that do not contain vowels:",c)}' $fn

    9. Write an awk script to find the number of characters, words and linesin a file.

    echo "enter a file name"

    readfn

    awk '{ w=w+NF

    c=c+length($0)}

    END{ print("no. oflines:",NR)

    print("no. ofwords:",w)

    print("no. ofcharacters:",c)

    }' $fn

    10. Write a C program that makes a copy of a file using standard I/O andsystem calls.

    #include

    #include

    #define MAX_SIZE 1000

    main() {

    int fd1,fd2,r1,w1;

    char buffer[MAX_SIZE];

    charsourceName[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);}

  • 7/29/2019 NP Lab Record

    4/154

    11. Implement in C the following Unix commands using System callsa) . cat#include

    #include

    #include

    #include

    #include

    int main(int argc,char *argv[])

    {

    int fd1,fd2;

    intn,count=0;

    fd1=open(argv[1],O_RDONLY);

    fd2=creat(argv[2],S_IWUSR);

    rename(argv[1],argv[2]);

    unlink(argv[1]);

    return(0); }

    b) mv#include

    #include

    #include

    #include

    #include

    int main(int argc,char *argv[])

    {

    int fd1,fd2;

    intn,count=0;fd1=open(argv[1],O_RDONLY);

    fd2=creat(argv[2],S_IWUSR);

    rename(argv[1],argv[2]);

    unlink(argv[1]);

    return(0);

    }

    12. Write a C program to emulate the Unixlsl command.#include #include

    #include

    main()

    {

    pid_tchildpid;

    childpid=fork();

    switch(childpid)

    {

    case -1:fprintf(stderr,"ERROR: %s \n", sys_errlist[errno]);

    exit(1);

    break;

  • 7/29/2019 NP Lab Record

    5/155

    case 0:

    execl("/bin/ls","ls","-l",NULL);

    perror("child fAiled to exec1 ls");

    printf("child code goes here");

    break;

    default:

    perror("parent failed to wait due to signal or error");

    printf("parent code goed here");

    break;

    }

    }

    13. Write a C program to create a child process and allow the parent todisplay parent andthe child to display child on the screen.

    #include

    main()

    {

    int a;

    a=fork();

    if(a>0)

    printf("parent \n");

    else

    printf("child \n");

    }

    14. Write a C program to create a Zombie process.#includemain()

    {

    intpid;

    pid=fork();

    if(0==pid)

    {

    printf("child process %d \n",getpid());

    }

    else{

    wait(0);

    sleep(30);

    printf("parent process \n");

    }

    }

    15. Write a C program that illustrates how an orphan is created.

    #includemain()

    {

    intpid;

  • 7/29/2019 NP Lab Record

    6/156

    pid=fork();

    if(0==pid)

    {

    printf("%d\n",getpid());

    sleep(5);

    printf("%d\n",getpid());

    }

    else

    {

    printf("bye from parent\n");

    }

    }

    16. Write a C program that illustrates how to execute two commandsconcurrently with a command pipe. Ex:- lsl | sort

    #include

    main()

    {

    int p[2],pid;

    pipe(p);

    pid=fork();

    if(0==pid)

    {

    close(p[0]);

    dup2(p[1],1);execl("/bin/ls","ls",(char *)0);

    perror("ls");

    }

    else

    {

    close(p[1]);

    dup2(p[0],0);

    execl("/usr/bin/wc","wc",(char *)0);

    perror("wc");}

    }

    17. Write a C program in which a parent writes a message to a pipe and thechild reads the message.

    #include

    main()

    {

    int p[2],pid;char *buf;

    buf=(char *) malloc(10);

    pipe(p);

  • 7/29/2019 NP Lab Record

    7/157

    pid=fork();

    if(pid>0)

    {

    printf("parent is writing on pipe");

    write(p[1],"hello",5);

    }

    else

    {

    read(p[0],buf,5);

    printf("child is reading %s \n",buf);

    }

    close(p[0]);

    close(p[1]);

    }

    18. Write a C program (sender.c) to create a message queue with read andwrite permissions to write 3messages to it with different priority numbers.

    #include

    #include

    #include

    #include

    structmsgbuf{

    longmtype;

    charmtext[40]; };

    main() {intmsqid,len,ret;

    structmsgbufmsgsend={0,"\0"};

    msqid=msgget((key_t)7,IPC_CREAT|0666);

    if(-1==msqid) {

    perror("msgget:");

    exit(1); }

    printf("enter msgtype:\n");

    scanf("%d",&msgsend.mtype);

    printf("enter msgtext:\n");scanf("%s",msgsend.mtext);

    len=strlen(msgsend.mtext);

    ret=msgsnd(msqid,&msgsend,len,0);

    if(-1==ret)

    {

    perror("msgsnd:");

    exit(1);

    }

    elseprintf("msgsent:\n");

    }

  • 7/29/2019 NP Lab Record

    8/158

    19. Write a C program (receiver.c) that receives the messages and displaysthem.

    #include

    #include

    #include

    #include

    structmsgbuf{

    longmtype;

    charmtext[40];

    };

    main()

    {

    intmsqid,len,type,ret;

    structmsgbufmsgread={0,"\0"};

    msqid=msgget((key_t)7,IPC_CREAT|0666);

    if(-1==msqid)

    {

    perror("msgget:");

    exit(1);

    }

    printf("enter the msg type:\n");

    scanf("%d",&type);

    len=sizeof(msgread.mtext);

    ret=msgrcv(msqid,&msgread,len,type,0);

    printf("ret=%d\n",ret);

    if(-1==ret){

    perror("msgrcv:");

    exit(1);

    }

    else

    printf("message type=%d message text=%s\n",msgread.mtype,msgread.mtext);

    }

    20. Write a C program that illustrates suspending and resuming processesusing signals.

    #include

    #include

    void fun(int k)

    {

    printf("signal is caught %d\n",k);

    }

    void bun(int p){

    printf("i am in bun %d\n",p);

    }

  • 7/29/2019 NP Lab Record

    9/159

    main()

    {

    signal(SIGINT,SIG_IGN);

    sleep(5);

    signal(SIGINT,fun);

    sleep(5);

    signal(SIGINT,bun);

    sleep(5);

    signal(SIGINT,SIG_DFL);

    for( ; ; );

    }

    21. Write a C program that implements a producer-consumer system withtwo processes (using Semaphores).

    #include

    #include

    #include

    #include

    #include

    voidabc()

    {

    printf("bye bye from child\n");

    exit(0);

    }

    void xyz()

    {printf("bye bye from parent\n");

    exit(0);

    }

    main()

    {

    intsemid;

    intpid;

    structsembuf 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();

    if(0==pid){

    sop.sem_num=0;

    sop.sem_op=-1;

  • 7/29/2019 NP Lab Record

    10/1510

    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);

    }

    }

    }

    22. Write client and server programs (using C) for interaction betweenserver and client processes using Unix Domain sockets.

    a) SERVER :-#include

    #include

    #include #include

    #define NSTRS3 /* 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"

    };

  • 7/29/2019 NP Lab Record

    11/1511

    main() {

    char c;

    FILE *fp;

    intfromlen;

    register int i, s, ns, len;

    structsockaddr_unsaun, fsaun;

    /*Get a socket to work with. This socket willbe in the UNIX domain, and will

    be astream 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. Weunlink the name first so that the bind

    won'tfail.

    The third argument indicates the "length" ofthe structure, not just the length of

    thesocket name.*/

    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, nswill be connected to the client.

    fsaun willcontain 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. */

  • 7/29/2019 NP Lab Record

    12/1512

    for (i = 0; i < NSTRS; i++)

    send(ns, strs[i], strlen(strs[i]), 0);

    /*Then we read some strings from the client andprint them out. */

    for (i = 0; i < NSTRS; i++) {

    while ((c = fgetc(fp)) != EOF) {

    putchar(c);

    if (c == '\n')

    break;

    }

    }

    /*We can simply use close() to terminate theconnection, since we're done with

    both sides. */

    close(s);

    exit(0);

    }

    b) CLIENT:-#include

    #include

    #include

    #include

    #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;

    structsockaddr_unsaun;

    /*Get a socket to work with. This socket willbe in the UNIX domain, and will be

    astream socket. */

  • 7/29/2019 NP Lab Record

    13/1513

    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {

    perror("client: socket");

    exit(1);

    }

    /*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 tosucceed, the server must already

    have boundthis address, and must have issued a listen()request.

    The third argument indicates the "length" ofthe structure, not just the length of

    thesocket 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 readingthe socket. */

    fp = fdopen(s, "r");

    /*First we read some strings from the serverand 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 theconnection, since we're done with

    both sides. */

    close(s);

    exit(0);

    }

    c) Write client and server programs(using c) for interaction between serverand client processes using Internet Domain sockets.

  • 7/29/2019 NP Lab Record

    14/1514

    23. Write a C program that illustrates two processes communicating viashared memory.

    a)#include

    #include

    #include

    #include

    #define SHMSZ 27

    main()

    {

    char c;

    intshmid;

    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

  • 7/29/2019 NP Lab Record

    15/15

    b)#include

    #include

    #include

    #include

    #define SHMSZ 27

    main()

    {

    intshmid;

    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. */

    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);}