Thursday, April 02, 2020

Writing my first C program in Linux

Recently I wrote my first C program in Ubuntu Linux for which I had a deadline. I was already familiar with C/C++ on Windows. It was quite a learning experience. My method was as follows:
  1. Search the internet for projects matching the problem definition. Result: There weren't any.
  2. Search examples/tutorials for terms in the problem definition like fork, poll.
  3. Write small demos. Modify and combine examples to solve the original problem. Result: Faced many difficulties during adaptation.
  4. Dive deeper and understand the details of concepts/terms that I am not well versed in, like pipes.
  5. Apply that deeper knowledge.
  6. Increase depth until the problem is solved in its entirety.
As you can see, I did not start by reading a lengthy Linux C fundamentals book. I focused on the problem at hand, tried shortcuts first and only spent more time on problematic points. I felt a lot of frustration while trying to hack my way out but I was determined enough to overcome constant failures. If you are working under time pressure, this is the fastest method of getting things done.

Notes:
  • To display processes starting with "node": ps -ef|grep node
  • To run as a background process, add & to the end.
  • Windows Subsystem for Linux, using Ubuntu with VS Code, tasks.json to build file (ctrl + shift+b)
  • pipes, socketpair, filedescriptor, dup2. 
  • Redirecting stdin
  • fork - exec
  • poll
  • Converting a string to a vector of strings, with space as delimiter
  • Difficulty of using strings. Writing and reading structures is much easier, to read a string after a write, you need to send EOF with close(fd), but then you have the problem of opening the filedescriptor again.
  • gcc, makefile, tar
  • Difficult to find bug in C: for (int i = 0; len; i++). Note that i< is missing.
  • When you print elements of a union structure, you will only get the last set element right.

No comments: