Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

I Killed My Report Script Mid-Write. Why the Output File Didn’t Notice, and How to Write Reports Safely

Killing a script does not undo writes the OS already accepted. Here is why a direct write can truncate a report, how temp-file-and-rename prevents partial reads on Linux, and why crash durability needs fsync.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Killing a process does not undo the writes it has already made. If a report script writes straight into its final output path, a kill at the wrong moment can leave a truncated or half-updated file, and the previous good report may already be gone. The usual fix is to write the new report to a temporary file in the same directory and then rename it over the target. On Linux, that makes the change visible in one step. It does not, by itself, protect the new data if the machine loses power, which needs an explicit fsync step.

What a kill actually interrupts

When you stop a script with SIGTERM or SIGKILL, the operating system stops the process at its next scheduling point. It does not reach back into the kernel and cancel system calls that have already completed. Any bytes the kernel accepted through write() before that moment are part of the file’s state. Your script’s unfinished work is the part that disappears.

As an Amazon Associate I earn from qualifying purchases.

That is why the output file can look untouched in one run and badly damaged in another. The outcome depends on exactly which step was in progress when the process died, not on the fact that the process was killed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why a direct write can leave a broken report

A common report script opens its destination path, writes the contents, and closes the file. The sequence looks like this:

#1 Best Overall
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400) | Everyday HDD storage. Plug-and-play backup. Windows & macOS. Adobe CC trial included. 1-Year Warranty
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
  1. Open the destination with truncation, which empties the existing file immediately.
  2. Write one or more chunks of new content.
  3. Close the file.

If the process is killed after step 1 and before step 2 finishes, the old report is already gone and the new one is incomplete. If it is killed during step 2, a reader sees a file that stops partway through. Only a kill after step 3 leaves a complete new file. Any reader or downstream job that opens the path during the write can see the same partial state.

Buffering makes this harder to predict. Data may sit in a library or kernel buffer and never reach the file before the kill, so the file on disk can be shorter than what your code thought it had written.

Rank #2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
  • Easily store and access 5TB of content on the go with the Seagate portable drive, a USB external hard Drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Why a successful write call is not a durability promise

The Linux write(2) manual describes two properties that matter here. A call can return after writing fewer bytes than requested, and it can be interrupted by a signal before any bytes are written or after some have been. Well-written libraries loop until all the bytes are accepted, but the manual also states plainly: “A successful return from write() does not make any guarantee that data has been committed to disk.”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

So a clean return from a write tells you the kernel accepted the bytes. It does not tell you the bytes will survive a crash.

Rank #3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Making the update appear in one step

The safe pattern is to stage the complete new report under a temporary name in the same directory as the target, make sure it is fully written and closed, and then rename it over the target. On Linux, a rename(2) within one filesystem replaces the destination name in a single step, so readers see either the old file or the new one, never a mix.

Three requirements make this work in practice:

  • Same filesystem. The temporary file must sit in the target’s directory. A rename across filesystems is a copy followed by a delete, which is not atomic and can fail.
  • Finish before renaming. Only rename after the write has completed without error and the file has been closed.
  • Clean up leftovers. If the process is killed mid-stage, a temporary file remains. The target is still intact, so the leftover is harmless, but a later run or a cleanup job should remove stale .tmp files.

A Node.js example (v22.23.3)

The following function uses the promise-based node:fs/promises API. It writes the report to a unique temporary file, flushes it to storage, closes it, and renames it over the target.

Rank #4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue | Everyday HDD storage. Plug-and-play backup. Windows & macOS. Adobe CC trial included. 1-Year Warranty
  • Easily store and access 4TB of content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
import { open, rename, unlink } from 'node:fs/promises';
import path from 'node:path';
import { randomUUID } from 'node:crypto';

export async function writeReportAtomically(target, contents) {
  const dir = path.dirname(target);
  const tmp = path.join(dir, `.${path.basename(target)}.${randomUUID()}.tmp`);
  try {
    const fh = await open(tmp, 'wx');
    try {
      await fh.writeFile(contents);
      await fh.sync();
    } finally {
      await fh.close();
    }
    await rename(tmp, target);
  } catch (err) {
    await unlink(tmp).catch(() => {});
    throw err;
  }
}

This version gives atomic visibility. It does not flush the directory entry, so a power loss right after the rename can still roll back the rename on some systems. The next section covers that step.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Two details in the Node.js API matter here. fs.writeFile given a file name replaces the existing file. Given a file descriptor, it does not replace the file; it writes from the descriptor’s current position. Also, the flush option of writeFile defaults to false. When set to true, Node.js calls fsync after a successful write. That option flushes data, but it does not turn a direct write into an atomic one. You still need the temporary file and rename.

Best Value
Sale
UnionSine 500GB Ultra Slim Portable External Hard Drive HDD-USB 3.0 | for PC, Mac, Laptop, PS4, Xbox one, Xbox 360-(Black)
  • [Upgraded Version] - This external hard drive features a mirrored logo stripe combined with a striped anti-slip design, and the rounded corners of the casing make it easier to grip. The stripes also have a heat dissipation function, ensuring stable and fast data transfer.
  • 【Ultra-thin and quiet】 - The motherboard adopts JMicron 578 noise-free solution, giving you a quiet working environment. Lightweight and portable size designed to fit in your pocket for easy portability.
  • 【Ultra-Fast Data Transfers】 - Pairing this external hard drive with JMicron 578 solution USB 3.0 and USB 2.0 interfaces enables blazing-fast data transfer. It boasts theoretical read speeds of up to 125MB/s and write speeds of up to 103MB/s.
  • 【Plug and Play】 - With no software to install, just plug it in and the drive is ready to use.The hard disk chip is wrapped with an aluminum anti-interference layer to increase heat dissipation and protect data.
  • 【What You Get】 - 1 x Portable Hard Drive, 1 x USB 3.0 Cable, 1 x User Manual, Gift-type shell packaging ,Three-year manufacturer's warranty and free technical support services.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Atomic visibility is not crash durability

These are separate guarantees, and they are often confused.

  • Atomic visibility means other readers see the old file or the new file, never a partial one. A rename in one filesystem provides this.
  • Crash durability means the new contents and the new directory entry are on persistent storage after a power loss or reboot. The Linux fsync(2) manual says the call transfers all modified in-core data of the file to storage so it can be retrieved after a system crash or reboot. However, it does not necessarily ensure that the directory entry containing the file is on disk.

Linux filesystem documentation warns that without explicit synchronization, a system crash can leave unexpected contents. To close that gap, sync the directory after the rename. On Linux, you can open a directory and call fsync on it. The following addition to the function above does that:

  await rename(tmp, target);
  const dirHandle = await open(dir, 'r');
  try {
    await dirHandle.sync();
  } finally {
    await dirHandle.close();
  }

Opening a directory this way works on Linux and other POSIX systems. It is not a portable technique, and it may fail on Windows, which needs its own documented approach.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Comparing the three approaches

Approach What a reader can see during the write If the process is killed mid-run After a power loss or machine crash
Direct write to the final path Truncated or partially updated file Old report may be lost; new report incomplete Not guaranteed; no sync step
Temporary file, then rename (no sync) Old file or new complete file (same filesystem, Linux) Old report intact; stale temporary file may remain Not guaranteed; new data and rename may not be on disk
Temporary file, sync file, rename, sync directory Old file or new complete file (same filesystem, Linux) Old report intact; stale temporary file may remain Documented Linux behavior for fsync; depends on the filesystem and storage hardware honoring the flush

Choose the row that matches your requirement. If readers must never see partial output, use the temporary-file approach. If the report must also survive a power failure, add both sync steps.

Where these guarantees stop

  • Other operating systems. Windows, macOS, and BSD systems have their own rename, replacement, and sync behavior. The Linux guarantees described here do not transfer automatically.
  • Network filesystems. NFS, SMB, and similar mounts can weaken or change rename and sync semantics. Check your mount’s documentation before relying on this pattern.
  • Multiple writers. Two scripts writing the same target can each rename over the other. Use a lock or a single writer if concurrent runs are possible.
  • File metadata. The new file takes its permissions and ownership from the staged file, not from the old report. Set them explicitly if downstream tools depend on them.

After a kill: what to check

  • Confirm the target path. If you used the temporary-file pattern, it should contain the last complete report.
  • Look for leftover .tmp files in the output directory and remove them only after confirming no run is still active.
  • If the target is truncated, it was written with a direct write. Restore it from a backup or rerun the script. The earlier version cannot be recovered from the file itself.

Once the script uses the staged pattern, a kill during generation leaves the previous report in place. The partial work exists only as a temporary file, which is why the output file never noticed.

Quick Recap

Bestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400) | Everyday HDD storage. Plug-and-play backup. Windows & macOS. Adobe CC trial included. 1-Year Warranty
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400) | Everyday HDD storage. Plug-and-play backup. Windows & macOS. Adobe CC trial included. 1-Year Warranty
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$129.99
Bestseller No. 2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$219.99
Bestseller No. 3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80
Bestseller No. 4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue | Everyday HDD storage. Plug-and-play backup. Windows & macOS. Adobe CC trial included. 1-Year Warranty
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue | Everyday HDD storage. Plug-and-play backup. Windows & macOS. Adobe CC trial included. 1-Year Warranty
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$189.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.