Search

shuf: To shuffle the contents of a file

The command shuf can be used to shuffle the lines of a file passed to it as input.
Example if we have a file,temp, with the following contents

temp:



We can shuffle the lines of the file randomly using shuf.



We can store the output in a new file using the -o option i.e



The output would be written to file temp1.
We can also create a random series of numbers using shuf, by using passing the options -i.



If we want all the numbers in one line and not in different lines we can add the options "-z"


Different ways to clear the terminal

Here are 5 different ways of clearing the terminal .

1. Using keyboard:



2. Command-1:



3. Command-2:



4. Command-3:



5. Command-4:

modprobe: FATAL: Module module.ko not found.

If we insert a module, say module.ko, using modprobe as below



We will get the error



This is because, we don't have to add the ".ko" extension while using modprobe.
Thus this will work


Coloring the output of cat

The "cat" command is used to view the contents of a file with out opening it.
The cat displays the contents of the file in the same color as that of the terminal. This can be changed and cat can be made to display the text in a different color. This can be done using the command "tput".
We can chnage the terminal font using tput as shown below.



For e.g.



Now we will combine this with cat .
Let us say we have a file temp

temp:





Output:



We can put this in a script and allow the user to pass the number for the color as well as the file to be displayed on the command line.

cat_color:



Save it and give it execute permissions.



Execute it just like the cat command



Output:



To make this script to work like a command we can add the path to the script in the PATH as given in the post Making a script available in all folders or copy the script into /bin directory.

Tracking the executing time of a process.

The command "ps" is used to list the processes running in the system and by adding various options to it we can get different informations regarding a process.
To find the time from which a proces has been executing we can use the option etime i.e.


For example, let us createa bash script that will run for 60 seconds



save it and give it execute permissions.



Execute it and put it in the back ground.



Now use the command ps to find the running time of the script.



We can see in the last column that process "script" has been running from 16 seconds.
If we execute ps again after a few secods we can see the change in the value.



Thus we can track the execution times of processes using ps.

Using renice to change the priority of a process

In the post "Using nice" we saw how we can assign a custom nice number to a process while launching it.
If we want to change the nice number of a process that is already running, then we can use the command renice.
The syntax of renice is



To find the pid of a process we can use the command pidof.
For example if we are running the gedit editor and want to get the pidof gedit, we can use



This pid can be used with the command renice. But before renice we can find the command currnet nice value of process by using the ps command



We can see that the current noice number of gedit is "-1". To change it to -5 we can use renice.



If we run ps now , we will notice the change in the nice number of the process.



The other options of the renice are explained in the man pages.

Using nice to assign priority to process

Linux maintains the priority of normal processes using a number called as the nice number.
The number ranges from -20 to +19 and smaller the number higher is the priority.
The name nice signifies that higher the nice value of a number the nicer it is to other processes.
To view the nice values of a process we can use the command "ps" as below.



In the above output the first column is the command or the process name, the second is the process id and the third is the nice value of the process.

The default nice value of a process is 0, thus most of the processes have a nice value 0.
We can launch a process with a nice value we want by using the command nice.
For example if we want to launch the gedit editor with a nice value of -1 we can do it using



Now if we do the process listing as above we should see the gedit listed with a nice value of -1.



Thus if we want to set a process to have a high priority we can start the same with a low nice value,lowest possible being -20.


rm: cannot remove `temp': Is a directory

The command "rm" is used to remove or delete files. When it is used to delete a folder you might see this error
For example if we try to delete a directory named temp



This is because "rm" be default deletes only files and to be remove a directory we need to pass the option "-r" with the command i.e.


Formatting text files using fmt

The command fmt allows us to format text file easily.
We saw how to wrap text using the command fold, in the post "Wrapping lines in a text file to specific width"
The command fmt gives more feature than fold gives.
For example let us say we have a file with the following contents
data:



By default fmt wraps text at 75 columns .



The number of columns to be wrapped at can be changed by the option -w



In the above command we have asked fmt to wrap text at 90 columns. If any line does not have requested number of columns fmt by default moves text line to the current line. Thus we seen in the above output that the text "fmt allows" has been moved up to line 1.
But unlike fold, fmt does not split words in between and if the word is exceeding the requested number of columns the whole words is moved to next line.
We can prevent fmt from moving text from the next line if the current line does not have the requested number of columns by using the option "-s"



Thus we can see that only if lines exceed 90 columns it will be wrapped else no new text is added to shorter lines.
Another useful feature of fmt is it can format the spacing between words and lines to be same across the whole file. If we add the "-u" option with the command then every word is separated by one space and every line by two spaces.



We can see in the output that the extra spaces after the words "the" and "allows" has been removed and made into a single space.
The lines that need to be formatted can be restricted by using the option -p



We can see that the line that starts with the string "This" is only formatted and the next line is not formatted.
Thus the basic formatting of text files is pretty easy using fmt.

What is cross compilation

The desktops and laptops that we use in our daily lives are mostly of x86 architecture. Thus when we compile a program using the usual compilers like gcc,turbo c etc the executable generated is compatible with x86 only and this can not be used to execute the same program on any other architecture.
For example consider this simple program

hello.c :


Now let us compile this using gcc



This generates an executable hello. To find out more details about this executable run the command "file" on the executable.



The output of the "file" command clearly indicates that "hello" is a 32 bit executable for intel 80386.
If we try to execute the same executable on another architecture like arm, it will not execute and will throw an error.

Other architectures like arm are generally in a very restricted environments where programming is not as easy as it is on PCs.
Thus to aid in programming for other architectures on PCs itself, special compilers exist and when a code is compiled using these special compilers, the executable generated will be for the architecture for which the compiler is supposed to generate for.
For example there is a compiler for arm from the GNU ,"gnuarm", available at http://gnuarm.com, which can be used to compile c programs on x86 machines(PCs) and generate executable for arm.
This process of generating executable for one architecture while compiling the code on another architecture is termed as cross compilation.
Compile the above program using the gnuarm compiler

Now use the command "file" on the executable



We can see that the executable is for 32 bit arm, and if we try to execute this on our PCs, It does not execute and throws an error as shown below.



Using fork and exec

We have seen the introducition to using fork as well as using the exec family of calls in the following posts.
Now we can combine these two to create a child using fork, which executes a differnt program than the parent using exec.
The following program is an example for doing the same.
Let us create a simple program that we will execute as the child process.

hello.c



Compile it and create an executable named "hello".



Now we will use execl to execute the "hello" executable from the child.
fork_exec.c



Save the program and compile it



Execute it



Output:



We can see from the output that the child has executed the "hello" program successfully and the parent has contiued with its normal operations.
Thus we can create a child and make it to launch any new process using the combination of fork and exec.

Changing the delimiter of read

The read command is used to accept value for a variable as input. Read,by default, continues to accept input untill the return key is not pressed. Thus the return key acts are the delimiter.

The delimiter can be set to any other chatacter we want by using the option "-d" with read.
i.e.



For example :



In the above case "," will act as the delimiter and read will stop accepting input as soon as "," is entered.

Using execv

execv like all other calls of the exec family,creates a new process replacing the current process.

The syntax of execv is



Arguments:



The operation is exactly same as that of execve as described in "Usage of execve". The only differece is that execv does not take the third argument



Here is an example of using execv :

Let us take a program to print hello world.

hello.c :



compile this to generate the executable hello



Here is a program that will launch the executable hello using execv



Output:




Limiting the number of characters read

read is used to take input from the user and assign it to a variable. read by default continues to accept input as long as the user does not enter the return key.

But if we want the input to be limited to a specific number of characters we can d it by using the option "-n" with read. i.e.



where num is the number of characters that is to accepted as input. In this case the read will not wait untill user hits return, but exits as soon as num characters are entered.

For example :

The option "-n" will exit even if it encounters a return key before the num characters are entered.

To avoid this,and to make sure that user must enter num characters before exiting read we can use the option "-N" i.e.



with the option "-N" the return key is also treated as in input character and read exits only after num characters are entered.




Using execlp

In the post "using execl" we saw how to launch a new process replacing the current one using execl. But the limitaion of execl is that if we have to execute a shell command or any other script that is not in the current woring directory as the new process, then we have to pass the full path of the command or the script.

The workaround to passing the full path of the executable is to use the functon execlp.
The syntax of execlp is :



Arguments:



As the executable is searched for in the path specified by the variable PATH, if the path to the executable is added to PATH it will be executed by execlp,thus any custom command or script can also be launched.

For example, in the following program we are using execlp to execute the command echo, with out mentioning the path to echo, which is not possible using only execl.



Ouput :




Using break in scripting

Break is used In scripting to stop the execution of a loop before its completion .

For e.g.



In the above loop the number of iterations are 10 unless the user enters "n" as the input,choosing the stop the loop before 10 iterations.
On receiving "y" as input , break is called which stops the execution of loop and breaks out of it before it completes its 10 iterations .
break can also be used to get out of multiple loops at the same time, by passing the number of loops to break out of as an option i.e.



Where n is the number of levels of loop to break out of, it has to be a positive number.
For example, in the following script there are three levels of loop and the break is in the inner most loop, which is the level 3.
When the user enters "y" to break out of the loop, we call break 2 signifying that we want to break out of 2 levels of the loop and the control of the script goes to the outermost loop.

multi_break.sh



Save the script and give it execute permissions



execute the script



Output:



From the above output we can see that on entering "y" the control directly goes to the outermost loop that is the level 1, thus breaking out of two levels of the loop.


Answers to linux scripting quiz -1

Here are the answers to linux scripting quiz-1

1. #! is called as
Ans. shebang

2. Which of the following is not a kind of shell
Ans. dsh

3. [ is eqvivalent to
Ans. test

4. The difference between printf and echo is
Ans. Echo adds a new line after printing, printf does not

5. ". " is used to match
Ans. Any one character

6. Which of the following symbols is used as prefix to access the value of variables in scripting
Ans. $

7. The comparison operator " -eq " is used for
Ans. Numbers

8. A comment line in a script begins with
Ans. #

9. Every line in a shell script ends with
Ans. There is no rule

10. Scripts are made executable using the command
Ans. chmod


Using execl

execl is a one of the family of exec calls which act as front end to the execve.
In the post "Using execve" we saw how it can be used to launch a new process and also pass arguments to it. execl also launches a new process replacing the current one. The syntax of execl is



In execve we had to pass an array of pointers as argument, but in execl we can directly pass the pointers as arguments. These arguments should be NULL terminated.

Example:

Let us write a simple program to print the arguments passed to it.
hello.c:



By convention the first argument should always be the filename and we will be following the same.
Let us compile this and name the executable as "hello"



Now let us write a program to run the executable "hello" using execl.
execl.c



Compile the code and execute it.



Output:



Thus the program could successfully run the executable "hello" and also pass the arguments to it.
Also note that execl did not return to the calling function,else it would have printed the "Error" statement after the call to execl.

A memory testing game in the terminal

The following script is a memory testing game that can be played on the terminal.



Save the script as memory_test.sh
Give it execute permissions



execute it



It will display a menu, prompting you to select either the level or help for the game.



Enter the number of your choice to make the selection.
If you enter 2, medium level will be selected. It will display a matrix of 3 X 3 characters as shown below.



Easy level displays a matrix of 2 x 2
Hard level displays a matrix of 4 x 4

The matrix will be visible for 5 seconds with in which try to remember all the characters and their locations.
After 5 seconds the screen will be cleared.
Then you will be prompted to enter any of the characters randomly by displaying "X" at the corresponding cell



3 wrong answers per character are allowed after which the game gets over and the actual matrix will be displayed again.

Anwers to Linux quiz - 1

Here are the answers to the quiz "Linux quiz -1"

1. What option of "ls" gives the listing according to the modified time
Ans. t

2. In which folder of linux filesystem does ".." and "." point to the same folder
Ans. /

3. The "-p" option of mkdir
Ans. Creates parent as well as it subfolders at the same time

4. Which option in "cat" adds line numbers to everyline in the output
Ans. n

5. The /bin directory generally holds
Ans. Executables

6. The output of "pwd" is what kind of path
Ans. Absolute Path

7. Which of the following is not a type of linux shell
Ans. crsh

8. ----- can change the password of a user
Ans. The user and the root

9.The output of the command "tac " is
Ans. The contents of the file in reverse

10. Which command changes the permissions of a file
Ans. chmod


Using execve

execve() is a function used to launch a process from with in another process.

The sytax of the function is :



Arguments:



The executable pointed to by "filename" replaces the current process. The function execve never returns to the calling function unless there is an error in executing the executable.

For example:

Let us write a program to print hello world and try to execute this from another program using execve.

hello.c



execve.c:



In the above program we are calling an executable "hello" and passig no arguments to it. We said that the execve never returns to the calling function if there is no error, to confirm this we have added a print statement after execve which should not get printed if the call is successful.

Now compile both the programs, make sure that the executable of hello.c is named as hello.



Execute the execve



Output:



Passing arguments:

To pass arguments in execve, we can make use of the second argument which is a pointer to an array of pointers.

For example



Let us modify the above hello.c to accept these arguments



execve.c



Compile and execute them as shown above and we should see the output



But the standard convention is to always pass the executable itself as the first argument and only then pass the other arguments. Thus to follow the convention we can modify the code as below.



execve.c





Executing a script

execve can also be used to run scripts that start with the line #! pointing to an interpreter.

For example

script.sh



save the script as sys.sh and give it execute permissions.





Compile and execute the program execve.c and we should see the output




Motherboard details from commad line

We can find out all the details about the motherboard in our system from the command line using the command lshw.

For example:



Output:


Answers to linux Distro quiz

Here are the answers to Linux Distro quiz

1. Which of the following distributions is not based on debian
Ans : open suse

2. yum is used as the package manager in
Ans: fedora

3. What was the name of the first release of ubuntu by canonical
Ans: Warty Warthog

4. Which of the following distributions is dedicated towards security and penertation testing for linux
Ans: backtrack

5. Which of the following is distribution is put together by Fermilab,CERN and other labs
Ans: Scientific linux

6. knoppix is
Ans: Distribution used mainly as a live cd

7. cinnamon is
Ans: GUI for the desktops

8. rpm files are used for installation in
Ans: redhat

9. fedora is developed and maintained by
Ans: redhat

10. Which of the following is not a desktop environment
Ans: brde


Linux distributions quiz

Linux Distro quiz

Linux Distro quiz

This is quiz based on Linux distributions.
  1. Which of the following distributions is not based on debian

  2. kubuntu
    linux mint
    open suse
    lubuntu

  3. yum is used as the package manager in

  4. linux mint
    bodhi linux
    fedora
    open suse

  5. What was the name of the first release of ubuntu by canonical

  6. Warty Warthog
    Feisty Fawn
    Yarrow
    Icecream Sandwhich

  7. Which of the following distributions is dedicated towards security and penetration testing for linux

  8. bodhi linux
    arch linux
    backtrack
    xubuntu

  9. Which of the following is distribution is put together by Fermilab,CERN and other labs

  10. Sabyon linux
    Arch linux
    Scientific linux
    Knoppix

  11. knoppix is

  12. Distribution used mainly as a live cd
    Used to repair boot sector
    Used to test new applications
    Just another distribution of linux.

  13. cinnamon is

  14. GUI for the desktops
    A new kind of shell
    A linux distribution
    A game in linux

  15. rpm files are used for installation in

  16. linux mint
    redhat
    ubuntu
    slackware

  17. fedora is developed and maintained by

  18. canonical
    redhat
    IBM
    Linux Foundation

  19. Which of the following is not a desktop environment

  20. xfce
    lxde
    enlightment
    brde

For any suggestions or queries mail me tux.think at gmail.com

Answers to the quiz: Answers to linux distro quiz

Using fork-2: Fork with wait.

In the post "Fork-1 : Introduction" we saw how a child gets created using the fork call.
Every parent process which forks a child has to keep track of its child/children. When a child terminates, the parent has to be informed about the termination and only then the child and its resources can be deleted from the system.
To be able to keep track of the child the system call wait() is used by the parent. The wait series of system calls allows the parent to track the changes in the states of the child process.
If the parent does not call wait on its child, then the child that gets terminated goes into a zombie state, and will be removed from the system only when it is assigned a new parent and that parent calls a wait on it or the system is shutdown.
There are three kinds of wait calls
wait:



waitpid:



waitid



The following code creates a child and waits on the same using the wait() system call.
The value filled in the variable status denotes the return status of the child and can be inspected using various macros, one of which is WIEXITSTATUS. The code below uses this macro to print the inspected value of status.

fork_wait.c



Save it,compile and excute it.



Output:



The following code uses waitpid and waits on the child using its pid and prints the status returned using WIEXITSTATUS.

fork_waitpid



Save it,compile and excute it.



output:



The following code used waitid to wait on the child. One of the field of siginfo_t structure, which is filled with the information regarding the child by the system call, is the return status of the child.

The same is printed after the wait in the example below.

fork_waitid.c

Save it,compile and excute it.



Output:

The other flags and options which can be passed to the wait system calls are mentioned in the man page of wait.

To view lines in the middle of a file

The command "head" is used to view the top lines of a file and command "tail" is used to view lines at the end.

What if we want to view the lines in between, that is neither from the top nor from the bottom.

For example let us say we have a file with the following contents:

file1 :



We can use the head command to view the top 3 lines



We can use the tail command to view the bottom 3 lines



But how to view the 3 lines in the center. Here are two ways of doing it.

Using a combination of head and tail



Using awk



script to delete the lines from a file having patterns present in another file

Let us assume we have set of patterns in a file as shown below.

data1:



And a file with the contents

data2:



If we want to search for the patterns in the file data1 and delete the lines that have the pattern in the file data2, we can do it using the following script.

del_pattern.sh :



save it in the same directory where the above two text files are saved,give it execute permission and execute it.



The while loop, loops through the file data1, reading on line at a time. The sed command in the while loop searches for the pattern in the file data2 and any line that has the pattern will be substituted by a blank line.

Instead of replacing with a blank line, we can delete the line using the following script.

del_pattern.sh



save it in the same directory where the above two text files are saved,give it execute permission and execute it.




Using grep to search in reverse

Grep ,which is used to search for a string or a pattern in the input,always starts searching from the beginning of the file.

But if we wanted to start the search from the back that is from the last line, then We can use grep in combination with tac.

tac displays the content of a file from last line to first line , if this is piped to grep it will be able to search in the reverse.

For example if we have a file with the name file1

file1



If we want to search for the string distros which is at the end we can use.


Answers to Linux Command quiz 1

Here are the answers to linux command quiz -1

1. Which option with the command rm is required to remove a directory
Ans: "-r"

2. The command used to display the manual pages for any command is
Ans: man

3. Which of following will show the first 5 lines of the input file
Ans: head -5

4. Which option of ls will show the hidden files
Ans: -a

5. The command cat -n file will
Ans: Add line numbers to every line of the output

6. The command echo -n hello will
Ans: Print hello and not add a new line after it

7. The command sort by default sorts
Ans: Text

8. Which of the following will list the users who currently logged in in the system
Ans: who

9. To change the password of a user we can use the command
Ans: passwd

10. Which command can be used to view the content of a file in reverse i.e from last line to first.
Ans: tac


read timeout in scripting

The command read is used in scripting to accept a value for a variable from the user.

The default operation of read is to wait infinetly for the user to enter a value. This behavour can be changed and read can be made to wait for a specific time only and abort after that.
This can be done by using the option "-t" with read i.e.



This will make read to wait for 5 seconds before aborting.
The script below shows how to use the option.

read_timeout.sh



The above script waits for 5 seconds for the user to enter a value,if the user fails to do so the script will continue to run and throw an error message.

Save it,give it execute permissions and execute it



If we do not enter any value at the read prompt, after 5 seconds we should see the following message.

Output:




Clearing the history of commands.

In the post "Deleting a command from the history" we saw how to delete command from the history of commands.

But what if we wanted to completely clear the history,i.e. remove all the commands from the history.
This can be done using the option "-c" with the history command.
For e.g. if our history command gives the following output.



Now we can clear it using



If we run the command history again,we will not get any output.



Note: You can not recover the history once it is deleted.

Using fork -1 Introduction

The function fork() is used to create a new process in linux.
The process which calls the fork is called as the parent and the process that gets created as a result of the fork call is called as the child.
The child process is by default an exact duplicate of the parent but both parent and the child have different process ids.
Once the fork is called from the parent, if a child is created successfully the fork returns the id of the child process to the parent .
The child which being the exact copy of the parent also has a fork call,but in this case the fork returns 0 to the child .
Let us write a simple code to see these steps in the operation.

In the following program :
We print a statement to mark the beginning of the program.
Then we create a child by calling fork.
We check the return value of fork. In the parent process the value will not be zero and in the case of the child the will be zero.
Using this fact we make the parent and child print their respective pids, showing that the two processes are executing independently.

fork.c



Note: We will cover the details of wait() another post

Save it and compile it



execute it



output:



We can see in the output that:
The return values of fork are different.
3974 which is the pid of the child is printed as the return value of fork by parent.
child prints the return value as 0.
Both child and parent print their respective pids.


"cp: omitting directory" error in linux

This is a common error a number of newbies in Linux might face when using the command "cp" to copy a directory.



The command cp is by default copies only files and if we try to copy a directory it will throw the above error.

To copy a directory using "cp" all we have to do is add the option "-r" which means recursively copy all the files from the source directory to the destination directory. i.e.




Reaction timer on the linux terminal

Here is a script that can be used as a reaction timer on the terminal of linux.

Reaction timers are used to calculate the time a user takes to react to an input or stimuli.

There are two variants one that can be run in the text mode and another that can be run in the terminal of GUI mode.

Text mode:

The following will turn the caps-lock led on and expects the user to hit any key on the keyboard as soon as the led is turned on. The time taken by the user to hit the key after turning on the led is displayed as the reaction time.

We will need to use two separate scripts one to light up the led and the other to record the reaction.

led_on.sh



key.sh



Save both the scripts and give them execute permissions



Note: that both have to saved in the same directory.

Now execute the script "led_on.sh".



After a delay between one to ten seconds the led of caps-lock will turn on.
The user has to hit any key on the keyboard as soon as it turns on.
The script will display the number of seconds or fraction of seconds the user took to react.

Note: The command "setleds" works only in the text mode, thus this script is not useful in the terminal of a GUI mode.

Note: You need to have permission to create files in the directory where you run this script as it creates a temp file during the execution and deletes it at the end.

GUI mode:

For the GUI mode the same script is modified and instead of turning on the led, the message "ON" is displayed and the user is expected to hit any key on the keyboard as soon as the message appears on the screen. The time user takes to hit the keyboard after the message appears is calculated and displayed as the reaction time.

led_on.sh



key.sh



The steps are same as for the script above, only difference being that instead of the led turning on, the message "ON" will be displayed on the terminal.


Keeping track of running time of script

if we want to track the time a script takes to run, we can make use of the inbuilt BASH variable SECONDS.

The value of SECONDS is always the time for which the script, in which it is called, is executing. For e.g.



Output :



Thus if we print the value of the variable SECONDS right at the end of the script we can get the time that the script took to complete.

Linux Basics commands quiz

Linux Basic Commands quiz

Linux Basic Commands quiz

This is a quiz on basic commands of linux.
  1. Which option with the command "rm" is required to remove a directory

  2. -d
    -f
    -r
    -i

  3. The command used to display the manual pages for any command is

  4. man
    manual
    help
    show

  5. Which of following will show the first 5 lines of the input file

  6. less -5 file
    head -5 file
    more -5 file
    show -5 file

  7. Which option of "ls" will show the hidden files

  8. -h
    -a
    -l
    -i

  9. The command "cat -n file" will

  10. Add a new line after every line of the output
    Add line numbers to every line of the output
    Will show only a count of number of lines in the file.
    Will not print any thing.

  11. The command "echo -n hello" will

  12. Print "hello" and add a new line after it
    Not print any thing
    Print "hello" and not add a new line after it
    Change the case and print HELLO

  13. The command sort by default sorts

  14. Text
    Numbers
    Any thing
    Special symbols

  15. Which of the following will list the users who currently logged in in the system

  16. login
    which
    who
    tty

  17. To change the password of a user we can use the command

  18. password
    passwd
    chpass
    su

  19. Which command can be used to view the content of a file in reverse i.e from last line to first.

  20. cat -r
    rev
    tac
    less

feel free mail tux.think@gmail.com for any corrections or clarifications.

Answers are given at : Answers to Linux commands quiz -1

Making read invisible

The command read is used to accept values from the user or from files in scripting.

The default operation of read is to echo the characters entered by the user on the terminal, but if the the characters being entered are that of password we might want to make the characers inviible or not appear on the screen.

This can be done using the "-s" option with read i.e.



Whatever the user enters for the above read prompt, will not be displayed on the terminal.

pthreads-3: Canceling a thread

Threads once created using pthread_create,can some times be required to be stopped in between before they complete their execution.
This can be done using the function


Argument:


pthread_cancel will by default stop the thread immediately. This behavior can be modified by using the attribute pthread_setcancelstate.
In the program that executes as part of the thread, we can add a series of sleep, giving us enough time to see it creation and the calling the cancel from the parent thread.

Thus the function to be executed by the thread will be



Note: The working of pthread_create is given in the post pthread creation

In the main thread, we will wait for a while after creating the thread and then call the pthread_cnacel.



After calling the pthread_cancel, we also need to call pthread_join to terminate the thread successfully.
The return value recieved by pthread_join on a cancelled thread is PTHREAD_CANCELLED, which is equal to integer "-1".
Thus let us print the return value and see what the thread returned.
The full code will look as follows.

cancel_create.c



Compile it using the -pthread option and execute it.



Output:



Thus we see that the thread stopped executing before finishing the for loop and the return value is -1, which indicates that the thread was cancelled using pthread_cancel

Follow by Email