Friday, February 18, 2011

Problem in swap code

Our only one blog fan, m3rlinez, told me that the one line swap code that I wrote in the previos entry cannot use when two variables are the same allocation such as

a[i] ^= a[j] ^= a[i] ^= a[j]; // when i = j

Thanks him to pointed this issue.

Wednesday, February 16, 2011

double fork magic

เริ่มที่ zombie process

zombie process คืออะไร
zombie process คือ process ที่ทำงานจบแล้วแต่ตัวมันยังอยู่ใน process table ของ OS เพื่อรอให้ parent process มาอ่านค่า exit status ของมัน แต่ก็ไม่มาอ่านซักที

แล้วเมื่อไหร่ parent process จะมาอ่าน exit status
เป็นไปได้สองทาง
  1. ในโค้ดเรียก function wait ( pid_t wait(int *stat_loc) ) แล้วโปรแกรมจะหยุดรอจนกว่า process ลูกจะทำงานเสร็จ
  2. เขียน signal handling ให้จัดการ SIGCHLD (SIGCHLD เป็น signal ที่ส่งมาบอกว่า process ลูกทำงานเสร็จแล้ว ให้ parent process ไปจัดการต่อด้วย)

double fork คืออะไร
double fork เป็นรูปแบบการเขียนโค้ดแบบหนึ่งที่ไว้ป้องกันการเกิด zombie process การเขียนโค้ดแบบ double fork นี้ใช้ประโยชน์จากการที่เมื่อ parent process จบการทำงานในขณะที่ child process ยังทำงานไม่เสร็จ โดย child process นั้นจะกลายเป็น process ลูกของ init process แทน ซึ่งจะคอยกำจัด child process พวกนี้ภายหลัง (init process คืออะไรอะเหรอ โอ๊ย เรื่องมันยาว)

แล้วตกลงมันทำงานยังไงหละว้อย
ยกตัวอย่างเปรียบเทียบให้เห็นภาพเลยละกัน
  1. ตัวอย่างแรกของการเกิด zombie สมมติว่ามี process A fork ลูกออกมาเป็น process B และเมื่อ B ทำงานเสร็จ A ไม่มาจัดการ SIGCHLD ที่ส่งมาทำให้ B กลายเป็น zombie
  2. ตัวอย่างการทำ double fork แทนที่ process A จะ fork B ออกมาเลย เราเขียนโค้ดให้ A fork process X ออกมาก่อน โดยหน้าที่อย่างเดียวของ X คือ fork B เมื่อ fork B เสร็จก็ให้ X จบการทำงาน ซึ่งเมื่อมาถึงขั้นนี้ B จะกลายเป็น orphan process และจะกลายเป็น process ลูกของ init เมื่อ B ทำงานเสร็จ init ก็จะมาจัดการเคลียร์ B ออกจาก process table ให้
ทีนี้ก็จะไม่มี zombie process อีกต่อไป

Friday, February 11, 2011

Swap two variable values code in one line.

First code pattern that comes to my mind when I want to swap two variable value is

int c;
c = a;
a = b;
b = c;

I found this code in every novice programming book, also in my programming class.
But I've heard one challenging problem (for me as a novice) that try to swap without temporary variable (that is c, in my code.) The code uses knowledge technique from logic class.

a = a ^ b;
b = a ^ b;
a = a ^ b;

The caret symbol (^) represents bitwise xor.
Recently, I found the code that written it in one line for making it more cool and less understanding that is

a ^= b ^= a ^= b;

Impressed!