Ubuntu mkdir – Linux: Create directory or folder using mkdir command

Linux: create directory or folder using mkdir command

ubuntu mkdir: In this article we will discuss how to create directory or folder using mkdir command. In Linux system, we can create new directories either from the command line or with the help of our desktop’s file manager.

mkdir :

  • It allows users to create or make new directories.
  • mkdir stands for make directory.

mkdir options :

  • -p, -parents : Add directory including its sub directory.
  • -v, -verbose : Print a message for each created directory.
  • -m, -mode : Set access privilege.

mkdir command syntax in linux :

The basic command for creating directories in Linux consist of the mkdir command and the name of the directory.

Syntax:
mkdir<dirname>

Note: if you will not provide a path then by default your file will be create in your current directory only. And if you want to create your directory somewhere else then you have to provide the path.

 Create a single directory in Linux with mkdir command :

To create a single directory in Linux, just provide folder name along with mkdir command.

Example:

ubuntu@Linux-VM:~/study$ mkdir project

It will create directory name ‘student’

Create multiple directories in Linux with mkdir command :

 If you want to create multiple directories in one command then provide all the names of the directories to mkdir command separated by space.

ubuntu@Linux-VM:~/study/student$ mkdir name rollno class section mobile_no

It created 5 directories i.e ‘name’, ‘rollno’, ‘class’, ‘section’, ‘mobile_no

We can also use verbose option(-v) which will help to create multiple directories. It will give a message after creating each directory.

Example:

ubuntu@Linux-VM:~/study$ mkdir -v class1 class2 class3
mkdir: created dictionary 'class1'
mkdir: created dictionary 'class2'
mkdir: created dictionary 'class3'
ubuntu@Linux-VM:~/study$

If we are trying to create a directory which is already exist then by default mkdir gives error. Let’s see with an example:

ubuntu@Linux-VM:~/study/student$ ls
name rollno class section mobile_no
ubuntu@Linux-VM:~/study/student$ mkdir section
mkdir: cannot create directory 'section': File exists

If we want a behavior which will not throws error if the directory is already exist and creates new directory if not exist then there is an option i.e -p option.

Example:

ubuntu@Linux-VM:~/study/student$ ls
name rollno class section mobile_no
ubuntu@Linux-VM:~/study/student$ mkdir section
ubuntu@Linux-VM:~/study/student$

Linux: create directory and subdirectories in one command – recursively : 

If we want to create a folder and subfolder in a single command then we need to provide -p option.

-p stands for parents, it means if a complete folder path is given and and any folder in the path is missing then it it create it. Let’s understand with an example suppose we want to create a folder ‘book’ and that the folder ‘book’ create folder ‘chapter’ and inside folder ‘chapter’ create folder ‘lines’. Nested folder structure should be book/chapter/lines. But if we try to create this nested folder with mkdir command then it will throw an error.

ubuntu@Linux-VM:~/study$ mkdir book/chapter/lines
mkdir: cannot create directory 'book/chapter/lines': No such file or directory
ubuntu@Linux-VM:~/study$

From the above example we understand that mkdir command cannot create missing parent folders by default. To automatically create missing parent folders we have use -p option with mkdir option.

ubuntu@Linux-VM:~/study$ mkdir -p book/chapter/lines

Linux: create directory with space in name :

 Example:

ubuntu@Linux-VM:~/study$ mkdir class test
ubuntu@Linux-VM:~/study$ ls
class test
ubuntu@Linux-VM:~/study$

From the above example we want to make a directory ‘class test’ but just giving the space it creates two directories i.e ‘class’ and ‘test’ which we don’t want it. So here it tricky to make a directory with space in name. we can’t directly create directory using mkdir. So we have to escape the spaces in the name while passing it to the mkdir command.

ubuntu@Linux-VM:~/study$ mkdir class\ test
ubuntu@Linux-VM:~/study$ mkdir 'course work'
ubuntu@Linux-VM:~/study$ ls
'class test' 'course work'
ubuntu@Linux-VM:~/study$

Create a dictionary with today’s date :

ubuntu@Linux-VM:~/study$ mkdir $(date +%Y-%m-%d)
ubuntu@Linux-VM:~/study$ ls
2021-04-30

Create a dictionary with today’s date and time :

 ubuntu@Linux-VM:~/study$ mkdir $(date +%Y-%m-%d--%H-%M-%S)
ubuntu@Linux-VM:~/study$ ls
2021-04-30—16-38-45

Pthread_detach example – POSIX: Detached vs Joinable threads | pthread_join() & pthread_detach() Examples

POSIX- Detached vs Joinable threads, pthread_join() & pthread_detach() Examples

Pthread_detach example: Guys who are looking for the perfect guide or tutorial for POSIX: Detached vs Joinable threads and pthread_join() & pthread_detach() examples? Can stay with us. This tutorial will explain & give you complete guidance while programming by using these Detached & Joinable Threads. Before going to learn Detached vs Joinable threads along with pthread_join() & pthread_detach() examples let’s start understanding what is thread and pthread?

About threads

Pthread_join examples: A thread is a semi-process that has its own stack and executes a given piece of code. threads within the same process run in shared memory space, it defined as an independent stream of instructions that can be scheduled to run as such by the operating system.

What is pthreads?

Pthread_detach: POSIX Threads usually referred to as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.

Thread can be run in two modes. They are as such,

1. Joinable mode
2. Detached mode

Joinable Thread & pthread_join()

Pthread_join example: A joinable thread will not release any resource even after the end of the thread function until some other thread calls pthread_join() with its ID.

Whereas pthread_join() is a blocking call, it will block the calling thread until the other thread ends.

We will pass two parameters in pthread-

1. The ID of the target thread

2. Address of (void *) i.e. (void **), it will point to the return value of thread function i.e. pointer to (void *).

pthread_join() will return non-zero value in case of error.

Example of pthread_join()

Pthread_join(): Below is the example for joinable thread,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    // Return value from thread
    return new int(6);
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will funtion threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff
    void * ptr = NULL;
    std::cout << "Waiting for thread to exit" << std::endl;
    // Wait for thread to exit
    err = pthread_join(threadId, &ptr);
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
        return err;
    }
    if (ptr)
        std::cout << " value returned by thread : " << *(int *) ptr
                << std::endl;
    delete (int *) ptr;
    return 0;
}

Output:

Thread Created with ID : 1407020804273336
Waiting for thread to exit
Thread Function :: Start
Thread Function :: End
value returned by thread : 6

Also Check:

Detached Thread & pthread_detach()

Pthread_detach: By default all threads are joinable, we will call pthread_detach() so to make a thread detached. A Detached thread automatically releases its allocated resources on exit. No other thread needs to join it.

#include <pthread.h>

int pthread_detach(pthread_t thread);

There is no way to determine its return value of the detached thread function.
pthread_detach() will return non zero value in case of error.

Output can change on your system because both the main and thread functions are running in parallel.

If the main function exits then all other threads will be exited.

pthread_detach() Example

Below is the example,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    std::cout << "Thread Function :: End" << std::endl;
    // Return value from thread
    return NULL;
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will funtion threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff
    err = pthread_detach(threadId);
    if (err)
        std::cout << "Failed to detach Thread : " << strerror(err) << std::endl;
    // Sleep for 2 seconds because if main function exits, then other threads will
    // be also be killed. Sleep for 2 seconds, so that detached exits by then
    sleep(2);
    std::cout << "Main function ends " << std::endl;
    return 0;
}

Output:

Thread Created with ID : 139703273027328
Thread Function :: Start
Thread Function :: End
Main function ends

Attach gdb to running process – How to attach gdb with running process

How to attach gdb with running process

Attaching gdb with running process

Attach gdb to running process: This article is all about knowing the concepts to debug a running application.

Many times when we work with any application, we need to debug a running application by attaching debugger with process during runtime.

So, the command used to attach the gdb with a running process is

gdb <PROCESS NAME> <PROCESS ID>

And the command used to search the process information like Process ID is

ps -elf | grep <Process Name>

Let’s see an example how to attach gdb debugger to a running process :

gdb attach to running process: Suppose we have a running process named “authenticator

To get the process information first

ps -elf | grep sample authenticator

As a result we will get process information including Process ID and others as below

0 S active 2009 1989 86 80 ... 00:00:14 ./authenticator

So here the process id we got 2009. Now by using the below command we will attach the gdb debugger with process.

gdb authenticator 2009

Note: If root permission is required then use below command

sudo gdb authenticator 2009

Which will give gdb command prompt

Reading symbols from /lib64/ld-linux-x86-64.so.2…Reading symbols from /usr/lib/debug//lib/x86_64-linux-gnu/ld-2.21.so…done.
done.
__lll_lock_wait_private () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:95
95 ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S: No such file or directory.
(gdb)

 

 

How to use pthread_create – POSIX : How to create a thread | pthread_create() example & Tutorial

What is thread Posix thread?

How to use pthread_create: Posix threads, referred as pthreads,  it is an execution model that lies independently from a language, as well as a from a execution model. It allows a program to control various different flows of work .

In this article we are going to discuss how to create a thread in C or C++ using POSIX Thread Library on Linux.

Thread operations can able to do  thread creation, termination,scheduling, synchronization, process interaction and data management .Each of thread shares the process address space and can access heap, global and static variables.A thread not able to manage a list of creadted threads,it also not able to know when the thread is creaded.

Create thread using pthread_create():

Pthread_create example c++: Every function is a thread,main is also a thread. If we have a function that we want to execute in parallel to main function.

void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    return NULL;
}

Here we are using  pthread_create() API to create a thread provided by POSIX.

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine) (void *), void *arg);

pthread_create() function is used to create or generate a new thread, with attributes mentioned as attr, in a process.

If there is no ant attt or attr is NULL, the default one is used. If the attributes specified by attr are modified later, the thread’s attributes are not affected. Upon successful completion, pthread_create() stores the ID of the created thread in the location referenced by thread.Pointer of the Thread ID, it will update the value in it.

So, now we are going to call pthread_create() by passing function pointer and other arguments .

// Thread id
pthread_t threadId;
// Create a thread that will function threadFunc()
int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
// Check if thread is created sucessfuly

We can use strerror() to get the detail of error.pthread_create() returns the error code . If thread is created  then it will return 0.And if  creation is failed it will return error code .

if (err)
    std::cout << "Thread creation failed : " << strerror(err);
else
    std::cout << "Thread Created with ID : " << threadId << std::endl;

Both the function, main function and other  threads runs  parallelly. But when main function ends it tasks, complete process exits and all the other thread will also  terminated. So  before main function ends we should wait for other threads to exit.Wait for other thread to complete POSIX Library provides a function for it i.e. pthread_join().

// Wait for thread to exit
err = pthread_join(threadId, NULL);
// check if joining is sucessful
if (err)
    std::cout << "Failed to join Thread : " << strerror(err) << std::endl;

It accepts a thread ID and pointer to store the return value from thread.

Below is complete example,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    return NULL;
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will function threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff in Main Thread
    std::cout << "Waiting for thread to exit" << std::endl;
    // Wait for thread to exit
    err = pthread_join(threadId, NULL);
    // check if joining is sucessful
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
        return err;
    }
    std::cout << "Exiting Main" << std::endl;
    return 0;
}

Output:

Thread Created with ID : 140054125654592
Waiting for thread to exit
Thread Function :: Start
Thread Function :: End
Exiting Main

Conclusion:

So in this article we have seen all about threads.We have also seen how to use pthread_create() and pthread_join().